简体   繁体   中英

Entity Framework Many To Many Relations: Search if contains all

I've been on this problem for a while and I have no ideia how to do it. I have this Model:

public class ConversationDB
{
     public int Id { get; set; }
     public virtual List<UserDB> Participants { get; set; }
}

and this

public class UserDB
{    
        public int Id { get; set; }

        public String Username { get; set; }
        public String FirstName { get; set; }
        public String LastName { get; set; }
        public String Email { get; set; }
        public String Password { get; set; }

        public virtual List<ConversationDB> Conversations { get; set; }
}

What I'm currently struggling on is searching for a conversation that has all elements of a list of participants say:

ConversationDB conversation = db.Conversations.Where(c => c.Participants.OrderBy(p => p.Username).SequenceEqual(partList.OrderBy(p => p.Username))).FirstOrDefault();

This code altough it gives me an error. What is the correct procedure I should take?

EDIT: I came with this ugly and stupid solution, but is basically what I want:

IEnumerable<ConversationDB> convs = db.Conversations.AsEnumerable();
foreach(UserDB u in partList)
{
      convs = convs.Where(c => c.Participants.Contains(u));
}

Why not :)

ConversationDB conversation = db.Conversations.Where(c => c.Participants.Count() == db.Users.Count());

I think, you can't add one user twice.

Or, more formal way:

ConversationDB conversation = db.Conversations.Where(c => db.Users.All(u => c.Participants.Contains(u)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM