LINQ Group and Members ViewModel for Membership Editting
-
26-10-2019 - |
Question
Given an EntityFramework POCO object model such as:
public class Group
{
public int GroupID { get; set; }
public string Category { get; set; }
public virtual ICollection<Member> Members { get; set; }
}
public class Member
{
public int MemberID { get; set; }
public string Name { get; set; }
public virtual ICollection<Group> Groups { get; set; }
}
Where a Many-To-Many Relationship is defined in the dbContext as follows:
Group GroupMember Member
------- ----------- -------
GroupID GroupID MemberID
Category MemberID Name
In order to allow group membership maintenance, I want to build a ViewModel that for any requested group, builds a list of all of the 'Member' objects in the system, along with a Flag indicating whether the 'Member' is already a member of the Group. The View will display a checkbox for the 'Flag' field, and the Member's Name in a list.
The user will be able to Check/Uncheck the checkbox to edit the list of Members in the Group.
I've been spinning my wheels trying to figure out a LINQ query to select this list and would greatly appreciate some pointers.
Solution
You mean like:
var model = from m in db.Members
orderby m.Name
select new GroupMemberRow
{
MemberID = m.MemberID,
Name = m.Name,
IsMember = m.Groups.Any(g => g.GroupID == groupId)
};
?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow