LINQ only returns one item in collection.NET Core EF Primary Key Error on context.SaveChanges()LINQ query on a DataTableDynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>Multiple “order by” in LINQUpdate all objects in a collection using LINQUsing LINQ to remove elements from a List<T>When to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?Returning IEnumerable<T> vs. IQueryable<T>LINQ Aggregate algorithm explainedGroup by in LINQ

Add an angle to a sphere

Is "plugging out" electronic devices an American expression?

Shall I use personal or official e-mail account when registering to external websites for work purpose?

Are white and non-white police officers equally likely to kill black suspects?

Does a dangling wire really electrocute me if I'm standing in water?

Piano - What is the notation for a double stop where both notes in the double stop are different lengths?

What is GPS' 19 year rollover and does it present a cybersecurity issue?

Does bootstrapped regression allow for inference?

Symmetry in quantum mechanics

What do you call something that goes against the spirit of the law, but is legal when interpreting the law to the letter?

What do you call words made from common English words?

How can I fix this gap between bookcases I made?

Why was the "bread communication" in the arena of Catching Fire left out in the movie?

Unbreakable Formation vs. Cry of the Carnarium

Lied on resume at previous job

What does 'script /dev/null' do?

Can the Produce Flame cantrip be used to grapple, or as an unarmed strike, in the right circumstances?

Need help identifying/translating a plaque in Tangier, Morocco

Why is my log file so massive? 22gb. I am running log backups

LWC and complex parameters

A poker game description that does not feel gimmicky

Are cabin dividers used to "hide" the flex of the airplane?

Can I find out the caloric content of bread by dehydrating it?

COUNT(*) or MAX(id) - which is faster?



LINQ only returns one item in collection


.NET Core EF Primary Key Error on context.SaveChanges()LINQ query on a DataTableDynamic LINQ OrderBy on IEnumerable<T> / IQueryable<T>Multiple “order by” in LINQUpdate all objects in a collection using LINQUsing LINQ to remove elements from a List<T>When to use .First and when to use .FirstOrDefault with LINQ?What is the Java equivalent for LINQ?Returning IEnumerable<T> vs. IQueryable<T>LINQ Aggregate algorithm explainedGroup by in LINQ






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have a Project model that has a collection of AppUsers assigned to be ProjectManagers or the more general case of Users



public class Project

public int ProjectID get; set;

[Required(ErrorMessage = " Please enter a project name")]
public string Name get; set;

public virtual ICollection<AppUser> ProjectManagers get; set;

public virtual ICollection<AppUser> Users get; set;



In my controller, I try to generate a list of all the project a particular AppUser is assigned to, regardless if they are in the ProjectManagers or Users collection



projectList = repository.Projects.Where(p => p.ProjectManagers.Contains(user) || p.Users.Contains(user));


However, if an AppUser is involved with more than one Project only the last Project populates this list. How do I ensure all associated projects are returned?



My AppUser model:



public class AppUser : IdentityUser

//literally does nothing at this point and
// is merely a placeholder until I add more



In my controller I use the List action method to display all the Projects related to the AppUser. This is the part that isn't working correctly, it's only returning a single Project



public async Task<IActionResult> List(int page = 1)

var user = await userManager.FindByNameAsync(User.Identity.Name);
if(user != null)

IQueryable<Project> projectList = GetUserProjects(page, user);
var model = GetProjectsListViewModel(projectList, page, user);
return View(model);

TempData["message"] = "User not found";
return RedirectToAction("Index", "Home");



The following methods are used to generate the lists and the models for pagination



 public ProjectsListViewModel GetProjectsListViewModel (IQueryable<Project> projectList, int page, AppUser user)

ProjectsListViewModel model = new ProjectsListViewModel();
model.Projects = projectList
.OrderBy(p => p.ProjectID)
.Skip((page - 1) * PageSize)
.Take(PageSize);
model.PagingInfo = new PagingInfo

CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = projectList.Count()
;
return model;


public IQueryable<Project> GetUserProjects(int page, AppUser user)

IQueryable<Project> projectList;
//IQueryable<Project> result;
if (user.UserName == "Admin")

projectList = repository.Projects;

else
p.Users.Contains(user)
return projectList;



EDIT
I noticed when I run proj.ProjectManagers.Add(appUser);, it will add that user as a ProjectManager but it looks like it it also deletes them from the ProjectManager collection of any other project they were previously assigned










share|improve this question
























  • Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

    – juharr
    Mar 22 at 1:53












  • @juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

    – coolhand
    Mar 22 at 1:54












  • It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

    – juharr
    Mar 22 at 1:56






  • 1





    Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

    – juharr
    Mar 22 at 2:02

















0















I have a Project model that has a collection of AppUsers assigned to be ProjectManagers or the more general case of Users



public class Project

public int ProjectID get; set;

[Required(ErrorMessage = " Please enter a project name")]
public string Name get; set;

public virtual ICollection<AppUser> ProjectManagers get; set;

public virtual ICollection<AppUser> Users get; set;



In my controller, I try to generate a list of all the project a particular AppUser is assigned to, regardless if they are in the ProjectManagers or Users collection



projectList = repository.Projects.Where(p => p.ProjectManagers.Contains(user) || p.Users.Contains(user));


However, if an AppUser is involved with more than one Project only the last Project populates this list. How do I ensure all associated projects are returned?



My AppUser model:



public class AppUser : IdentityUser

//literally does nothing at this point and
// is merely a placeholder until I add more



In my controller I use the List action method to display all the Projects related to the AppUser. This is the part that isn't working correctly, it's only returning a single Project



public async Task<IActionResult> List(int page = 1)

var user = await userManager.FindByNameAsync(User.Identity.Name);
if(user != null)

IQueryable<Project> projectList = GetUserProjects(page, user);
var model = GetProjectsListViewModel(projectList, page, user);
return View(model);

TempData["message"] = "User not found";
return RedirectToAction("Index", "Home");



The following methods are used to generate the lists and the models for pagination



 public ProjectsListViewModel GetProjectsListViewModel (IQueryable<Project> projectList, int page, AppUser user)

ProjectsListViewModel model = new ProjectsListViewModel();
model.Projects = projectList
.OrderBy(p => p.ProjectID)
.Skip((page - 1) * PageSize)
.Take(PageSize);
model.PagingInfo = new PagingInfo

CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = projectList.Count()
;
return model;


public IQueryable<Project> GetUserProjects(int page, AppUser user)

IQueryable<Project> projectList;
//IQueryable<Project> result;
if (user.UserName == "Admin")

projectList = repository.Projects;

else
p.Users.Contains(user)
return projectList;



EDIT
I noticed when I run proj.ProjectManagers.Add(appUser);, it will add that user as a ProjectManager but it looks like it it also deletes them from the ProjectManager collection of any other project they were previously assigned










share|improve this question
























  • Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

    – juharr
    Mar 22 at 1:53












  • @juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

    – coolhand
    Mar 22 at 1:54












  • It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

    – juharr
    Mar 22 at 1:56






  • 1





    Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

    – juharr
    Mar 22 at 2:02













0












0








0








I have a Project model that has a collection of AppUsers assigned to be ProjectManagers or the more general case of Users



public class Project

public int ProjectID get; set;

[Required(ErrorMessage = " Please enter a project name")]
public string Name get; set;

public virtual ICollection<AppUser> ProjectManagers get; set;

public virtual ICollection<AppUser> Users get; set;



In my controller, I try to generate a list of all the project a particular AppUser is assigned to, regardless if they are in the ProjectManagers or Users collection



projectList = repository.Projects.Where(p => p.ProjectManagers.Contains(user) || p.Users.Contains(user));


However, if an AppUser is involved with more than one Project only the last Project populates this list. How do I ensure all associated projects are returned?



My AppUser model:



public class AppUser : IdentityUser

//literally does nothing at this point and
// is merely a placeholder until I add more



In my controller I use the List action method to display all the Projects related to the AppUser. This is the part that isn't working correctly, it's only returning a single Project



public async Task<IActionResult> List(int page = 1)

var user = await userManager.FindByNameAsync(User.Identity.Name);
if(user != null)

IQueryable<Project> projectList = GetUserProjects(page, user);
var model = GetProjectsListViewModel(projectList, page, user);
return View(model);

TempData["message"] = "User not found";
return RedirectToAction("Index", "Home");



The following methods are used to generate the lists and the models for pagination



 public ProjectsListViewModel GetProjectsListViewModel (IQueryable<Project> projectList, int page, AppUser user)

ProjectsListViewModel model = new ProjectsListViewModel();
model.Projects = projectList
.OrderBy(p => p.ProjectID)
.Skip((page - 1) * PageSize)
.Take(PageSize);
model.PagingInfo = new PagingInfo

CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = projectList.Count()
;
return model;


public IQueryable<Project> GetUserProjects(int page, AppUser user)

IQueryable<Project> projectList;
//IQueryable<Project> result;
if (user.UserName == "Admin")

projectList = repository.Projects;

else
p.Users.Contains(user)
return projectList;



EDIT
I noticed when I run proj.ProjectManagers.Add(appUser);, it will add that user as a ProjectManager but it looks like it it also deletes them from the ProjectManager collection of any other project they were previously assigned










share|improve this question
















I have a Project model that has a collection of AppUsers assigned to be ProjectManagers or the more general case of Users



public class Project

public int ProjectID get; set;

[Required(ErrorMessage = " Please enter a project name")]
public string Name get; set;

public virtual ICollection<AppUser> ProjectManagers get; set;

public virtual ICollection<AppUser> Users get; set;



In my controller, I try to generate a list of all the project a particular AppUser is assigned to, regardless if they are in the ProjectManagers or Users collection



projectList = repository.Projects.Where(p => p.ProjectManagers.Contains(user) || p.Users.Contains(user));


However, if an AppUser is involved with more than one Project only the last Project populates this list. How do I ensure all associated projects are returned?



My AppUser model:



public class AppUser : IdentityUser

//literally does nothing at this point and
// is merely a placeholder until I add more



In my controller I use the List action method to display all the Projects related to the AppUser. This is the part that isn't working correctly, it's only returning a single Project



public async Task<IActionResult> List(int page = 1)

var user = await userManager.FindByNameAsync(User.Identity.Name);
if(user != null)

IQueryable<Project> projectList = GetUserProjects(page, user);
var model = GetProjectsListViewModel(projectList, page, user);
return View(model);

TempData["message"] = "User not found";
return RedirectToAction("Index", "Home");



The following methods are used to generate the lists and the models for pagination



 public ProjectsListViewModel GetProjectsListViewModel (IQueryable<Project> projectList, int page, AppUser user)

ProjectsListViewModel model = new ProjectsListViewModel();
model.Projects = projectList
.OrderBy(p => p.ProjectID)
.Skip((page - 1) * PageSize)
.Take(PageSize);
model.PagingInfo = new PagingInfo

CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = projectList.Count()
;
return model;


public IQueryable<Project> GetUserProjects(int page, AppUser user)

IQueryable<Project> projectList;
//IQueryable<Project> result;
if (user.UserName == "Admin")

projectList = repository.Projects;

else
p.Users.Contains(user)
return projectList;



EDIT
I noticed when I run proj.ProjectManagers.Add(appUser);, it will add that user as a ProjectManager but it looks like it it also deletes them from the ProjectManager collection of any other project they were previously assigned







c# linq asp.net-core






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 24 at 23:44







coolhand

















asked Mar 22 at 1:49









coolhandcoolhand

458318




458318












  • Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

    – juharr
    Mar 22 at 1:53












  • @juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

    – coolhand
    Mar 22 at 1:54












  • It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

    – juharr
    Mar 22 at 1:56






  • 1





    Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

    – juharr
    Mar 22 at 2:02

















  • Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

    – juharr
    Mar 22 at 1:53












  • @juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

    – coolhand
    Mar 22 at 1:54












  • It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

    – juharr
    Mar 22 at 1:56






  • 1





    Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

    – juharr
    Mar 22 at 2:02
















Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

– juharr
Mar 22 at 1:53






Does AppUser override GetHashCode and Equals? If not do you have the exact same reference in both projects? Because if you don't override Equals and GetHashCode then it will do reference equality and only match on the exact same object and not on one with an equivalent value.

– juharr
Mar 22 at 1:53














@juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

– coolhand
Mar 22 at 1:54






@juharr what would they need to be overridden to do? This is something I haven't implemented on this and am not quite sure how to begin. Right now AppUser extends IdentityUser but I have not added any additional properties

– coolhand
Mar 22 at 1:54














It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

– juharr
Mar 22 at 1:56





It depends on what you have in AppUser. Lets say you want to match on a Name property then you'd make the Equals compare the names and GetHashCode would just return the Name.GetHashCode.

– juharr
Mar 22 at 1:56




1




1





Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

– juharr
Mar 22 at 2:02





Actually if this is EF then you'd just need to change the code to match on whatever the PK is like Ashkan has in his answer.

– juharr
Mar 22 at 2:02












2 Answers
2






active

oldest

votes


















0














In here as there is no datetime in your project class, I assume that the project with bigger Id is the newer one:



var result = Projects
.Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
|| p.Users.Any(u => u.Id == user.Id))
.Select(x => new UserId = user.Id, Projects = x )
.GroupBy(p => p.UserId)
.Select(x => x.OrderByDescending(p => p.Projects.ProjectID).First().Project);


To get all projects of the user:



var result = Projects
.Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
|| p.Users.Any(u => u.Id == user.Id));





share|improve this answer

























  • I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

    – coolhand
    Mar 22 at 2:27











  • @coolhand yes there was an error in my code. please see my edited answer.

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:30











  • I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

    – coolhand
    Mar 22 at 2:41











  • Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:43











  • I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

    – coolhand
    Mar 22 at 2:46



















0














The issue was that I wasn't using a many-to-many joint table. So when I added an AppUser to a Project, it deleted the relationship between any previous objects. Thus, only one Project would be associated with a user. To fix this, I created the class:



public class ProjectManager

public int ProjectID get; set;
public Project Project get; set;

public string AppUserID get; set;
public AppUser AppUser get; set;



and added this collection to my AppUser class:



 public class AppUser : IdentityUser

public ICollection<ProjectManager> ProjectsAsManager get; set;



And added the following to my dbContext:



 modelBuilder.Entity<ProjectManager>()
.HasKey(ppm => new ppm.ProjectID, ppm.AppUserID );

modelBuilder.Entity<ProjectManager>()
.HasOne(pm => pm.AppUser)
.WithMany(p => p.ProjectsAsManager)
.HasForeignKey(pm => pm.AppUserID);

modelBuilder.Entity<ProjectManager>()
.HasOne(pm => pm.Project)
.WithMany(p => p.ProjectManagers)
.HasForeignKey(pm => pm.ProjectID);

base.OnModelCreating(modelBuilder);


After running a migration and update, a single user can now be associated with more than one Project as a ProjectManager






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291755%2flinq-only-returns-one-item-in-collection%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    In here as there is no datetime in your project class, I assume that the project with bigger Id is the newer one:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id))
    .Select(x => new UserId = user.Id, Projects = x )
    .GroupBy(p => p.UserId)
    .Select(x => x.OrderByDescending(p => p.Projects.ProjectID).First().Project);


    To get all projects of the user:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id));





    share|improve this answer

























    • I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

      – coolhand
      Mar 22 at 2:27











    • @coolhand yes there was an error in my code. please see my edited answer.

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:30











    • I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

      – coolhand
      Mar 22 at 2:41











    • Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:43











    • I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

      – coolhand
      Mar 22 at 2:46
















    0














    In here as there is no datetime in your project class, I assume that the project with bigger Id is the newer one:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id))
    .Select(x => new UserId = user.Id, Projects = x )
    .GroupBy(p => p.UserId)
    .Select(x => x.OrderByDescending(p => p.Projects.ProjectID).First().Project);


    To get all projects of the user:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id));





    share|improve this answer

























    • I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

      – coolhand
      Mar 22 at 2:27











    • @coolhand yes there was an error in my code. please see my edited answer.

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:30











    • I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

      – coolhand
      Mar 22 at 2:41











    • Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:43











    • I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

      – coolhand
      Mar 22 at 2:46














    0












    0








    0







    In here as there is no datetime in your project class, I assume that the project with bigger Id is the newer one:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id))
    .Select(x => new UserId = user.Id, Projects = x )
    .GroupBy(p => p.UserId)
    .Select(x => x.OrderByDescending(p => p.Projects.ProjectID).First().Project);


    To get all projects of the user:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id));





    share|improve this answer















    In here as there is no datetime in your project class, I assume that the project with bigger Id is the newer one:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id))
    .Select(x => new UserId = user.Id, Projects = x )
    .GroupBy(p => p.UserId)
    .Select(x => x.OrderByDescending(p => p.Projects.ProjectID).First().Project);


    To get all projects of the user:



    var result = Projects
    .Where(p => p.ProjectManagers.Any(pm => pm.Id == user.Id)
    || p.Users.Any(u => u.Id == user.Id));






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 22 at 3:00

























    answered Mar 22 at 1:57









    Ashkan Mobayen KhiabaniAshkan Mobayen Khiabani

    23.4k1868125




    23.4k1868125












    • I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

      – coolhand
      Mar 22 at 2:27











    • @coolhand yes there was an error in my code. please see my edited answer.

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:30











    • I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

      – coolhand
      Mar 22 at 2:41











    • Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:43











    • I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

      – coolhand
      Mar 22 at 2:46


















    • I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

      – coolhand
      Mar 22 at 2:27











    • @coolhand yes there was an error in my code. please see my edited answer.

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:30











    • I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

      – coolhand
      Mar 22 at 2:41











    • Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

      – Ashkan Mobayen Khiabani
      Mar 22 at 2:43











    • I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

      – coolhand
      Mar 22 at 2:46

















    I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

    – coolhand
    Mar 22 at 2:27





    I think this is most likely the answer but I'm getting an error on ProjectID of x.OrderByDescending(p => p.ProjectID).First()) stating "<anonymous type string: UserId, Project Project> does not contain a definition for 'ProjectID'"

    – coolhand
    Mar 22 at 2:27













    @coolhand yes there was an error in my code. please see my edited answer.

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:30





    @coolhand yes there was an error in my code. please see my edited answer.

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:30













    I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

    – coolhand
    Mar 22 at 2:41





    I think I'm misunderstanding. I'm trying to return an IQueryable<Project> projectList; but your result is string UserId, Project Projects

    – coolhand
    Mar 22 at 2:41













    Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:43





    Oh yeah, just add .Project after first. I just added it to the answer. ;) this happens when you answer at 7 am, and you haven't slept

    – Ashkan Mobayen Khiabani
    Mar 22 at 2:43













    I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

    – coolhand
    Mar 22 at 2:46






    I'm tracking what you're doing now (except the answer needs respository.Projects and First().Projects to pass), but I'm still getting the same result of a single project being returned

    – coolhand
    Mar 22 at 2:46














    0














    The issue was that I wasn't using a many-to-many joint table. So when I added an AppUser to a Project, it deleted the relationship between any previous objects. Thus, only one Project would be associated with a user. To fix this, I created the class:



    public class ProjectManager

    public int ProjectID get; set;
    public Project Project get; set;

    public string AppUserID get; set;
    public AppUser AppUser get; set;



    and added this collection to my AppUser class:



     public class AppUser : IdentityUser

    public ICollection<ProjectManager> ProjectsAsManager get; set;



    And added the following to my dbContext:



     modelBuilder.Entity<ProjectManager>()
    .HasKey(ppm => new ppm.ProjectID, ppm.AppUserID );

    modelBuilder.Entity<ProjectManager>()
    .HasOne(pm => pm.AppUser)
    .WithMany(p => p.ProjectsAsManager)
    .HasForeignKey(pm => pm.AppUserID);

    modelBuilder.Entity<ProjectManager>()
    .HasOne(pm => pm.Project)
    .WithMany(p => p.ProjectManagers)
    .HasForeignKey(pm => pm.ProjectID);

    base.OnModelCreating(modelBuilder);


    After running a migration and update, a single user can now be associated with more than one Project as a ProjectManager






    share|improve this answer



























      0














      The issue was that I wasn't using a many-to-many joint table. So when I added an AppUser to a Project, it deleted the relationship between any previous objects. Thus, only one Project would be associated with a user. To fix this, I created the class:



      public class ProjectManager

      public int ProjectID get; set;
      public Project Project get; set;

      public string AppUserID get; set;
      public AppUser AppUser get; set;



      and added this collection to my AppUser class:



       public class AppUser : IdentityUser

      public ICollection<ProjectManager> ProjectsAsManager get; set;



      And added the following to my dbContext:



       modelBuilder.Entity<ProjectManager>()
      .HasKey(ppm => new ppm.ProjectID, ppm.AppUserID );

      modelBuilder.Entity<ProjectManager>()
      .HasOne(pm => pm.AppUser)
      .WithMany(p => p.ProjectsAsManager)
      .HasForeignKey(pm => pm.AppUserID);

      modelBuilder.Entity<ProjectManager>()
      .HasOne(pm => pm.Project)
      .WithMany(p => p.ProjectManagers)
      .HasForeignKey(pm => pm.ProjectID);

      base.OnModelCreating(modelBuilder);


      After running a migration and update, a single user can now be associated with more than one Project as a ProjectManager






      share|improve this answer

























        0












        0








        0







        The issue was that I wasn't using a many-to-many joint table. So when I added an AppUser to a Project, it deleted the relationship between any previous objects. Thus, only one Project would be associated with a user. To fix this, I created the class:



        public class ProjectManager

        public int ProjectID get; set;
        public Project Project get; set;

        public string AppUserID get; set;
        public AppUser AppUser get; set;



        and added this collection to my AppUser class:



         public class AppUser : IdentityUser

        public ICollection<ProjectManager> ProjectsAsManager get; set;



        And added the following to my dbContext:



         modelBuilder.Entity<ProjectManager>()
        .HasKey(ppm => new ppm.ProjectID, ppm.AppUserID );

        modelBuilder.Entity<ProjectManager>()
        .HasOne(pm => pm.AppUser)
        .WithMany(p => p.ProjectsAsManager)
        .HasForeignKey(pm => pm.AppUserID);

        modelBuilder.Entity<ProjectManager>()
        .HasOne(pm => pm.Project)
        .WithMany(p => p.ProjectManagers)
        .HasForeignKey(pm => pm.ProjectID);

        base.OnModelCreating(modelBuilder);


        After running a migration and update, a single user can now be associated with more than one Project as a ProjectManager






        share|improve this answer













        The issue was that I wasn't using a many-to-many joint table. So when I added an AppUser to a Project, it deleted the relationship between any previous objects. Thus, only one Project would be associated with a user. To fix this, I created the class:



        public class ProjectManager

        public int ProjectID get; set;
        public Project Project get; set;

        public string AppUserID get; set;
        public AppUser AppUser get; set;



        and added this collection to my AppUser class:



         public class AppUser : IdentityUser

        public ICollection<ProjectManager> ProjectsAsManager get; set;



        And added the following to my dbContext:



         modelBuilder.Entity<ProjectManager>()
        .HasKey(ppm => new ppm.ProjectID, ppm.AppUserID );

        modelBuilder.Entity<ProjectManager>()
        .HasOne(pm => pm.AppUser)
        .WithMany(p => p.ProjectsAsManager)
        .HasForeignKey(pm => pm.AppUserID);

        modelBuilder.Entity<ProjectManager>()
        .HasOne(pm => pm.Project)
        .WithMany(p => p.ProjectManagers)
        .HasForeignKey(pm => pm.ProjectID);

        base.OnModelCreating(modelBuilder);


        After running a migration and update, a single user can now be associated with more than one Project as a ProjectManager







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 0:19









        coolhandcoolhand

        458318




        458318



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55291755%2flinq-only-returns-one-item-in-collection%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript