简体   繁体   中英

Filtering Data in Many To Many Relationship in Entity Framework

I have a simple Many to Many relationship models in my project.

Here are my classes:

public class AppUser{
   public string Id { get; set; }
   public string Name { get; set; }

   public List<AppUserBlogs> AppUserBlogs { get; set; }
}
public class Blog{
   public string Id { get; set;}
   public string Title { get; set;}
   public string Body { get; set;}

   public List<AppUserBlogs> AppUserBlogs { get; set; }
}

Okay so what I'd like to achive in here is, I'd like to retrive all the blogs but instead the ones already a User has.

I can do its opposite, which is retreiving list of blogs of a specific user,

public List<Blog> GetBlogsByUser(AppUser user)
{
     using (var context = new BlogContext())
     {
         var blogs = context.Blogs.AsQueryable();

         if (!string.IsNullOrEmpty(user.Id))
         {
               blogs =  blogs
                           .Include(i => i.AppUserBlogs)
                           .ThenInclude(i => i.AppUser)
                           .Where(i => i.AppUserChasses.Any(a => a.AppUser.Id == user.Id));
         }

         return blogs.ToList();
    }
}

I actually need the opposite of this method. For example, lets assume that there are 20 Blogs in my Blogs Table. And 4 of them are User-1's Blogs. (BlogId-1 -> UserId-1 | BlogId-2 -> UserId-1 etc...).

So, in another view, I'd like to show to User-1, the other 16 Blogs which User-1 doesnt have.

I hope I did ask it clearly...

Thank you for your time!

Just negate the where clause:

.Where(i => !i.AppUserChasses.Any(a => a.AppUser.Id == user.Id));

I did solve this problem changing the method into this one. But I'm still not sure that if it is the best solution..

public List<Blog> GetAllExceptUserBlogs(AppUser user)
{
     using (var context = new BlogContext())
     {                
         var allBlogs = context.Blogs
                               .Include(i => i.AppUserBlogs)
                               .ThenInclude(i => i.AppUser)
                               .ToList();
         var selectedUser = context.AppUsers
                                   .Include(i => i.AppUserBlogs)
                                   .ThenInclude(i => i.Blog)
                                   .Where(i => i.Id == user.Id)
                                   .FirstOrDefault();
         List<Blog> tempBlogList = new List<Blog>();

         foreach (var blog in allBlogs)
         {
              if(!selectedUser.AppUserBlogs.Select(i => i.Blog).Contains(blog))
              {
                   tempBlogList.Add(blog);
              }
         }

         return tempBlogList;               
    }
 }

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