0

I have two classes:

public class User
{
    public User()
    {
        this.Groups = new List<Group>();
    }

    public long Id { get; set; }
    public string Name { get; set; }

    public IList<Group> Groups { get; set; }
}

and

public class Group
{
    public Group()
    {
        this.Users = new List<User>();
    }

    public long Id { get; set; }
    public string Name { get; set; }

    public IList<User> Users { get; set; }
}

I have defined a many-to-many relationship with OpenAccess by using a join table:

mapping.HasAssociation(user => user.Groups).WithOpposite(group => group.Users).MapJoinTable("UserGroup", (user, group) => new
            {
                UserId = user.Id,
                GroupId = group.Id
            });

I would like to get all users who are associated to the group x.

How to write the linq request ?

I finally want to remove the group x after removing of all links (user/group) to this group. Or is it possible to make it automatically by a cascade delete ? I am interesting by the two solutions.

profou
  • 197
  • 1
  • 17

1 Answers1

0

You can select Users from Group using sample code below

var allUserInGroup = Group.Where(group => group.Id == id).Select(group => group.Users).ToList();

For the delete part:

if(!group.Any(g => g.Users))  {  // assume group is IQueryable/IEnumerable
   context.Group.Remove(group);
   context.SaveChanges();
}
Kien Chu
  • 4,735
  • 1
  • 17
  • 31
  • The selection gives me a trackedList[User]. How to use it in a loop ? How to convert it to a IEnumerable (List for example) ? – profou Oct 02 '15 at 11:14
  • I have an error "Unknown method Any(?)" with the delete part. – profou Oct 02 '15 at 11:53
  • @profou: I edited my answer. You just call `ToList()` in the first part. The second part, the group must be IEnumerable or IQueryable – Kien Chu Oct 02 '15 at 14:01