【问题标题】:Filtering Data in Many To Many Relationship in Entity Framework在实体框架中过滤多对多关系中的数据
【发布时间】:2019-10-31 16:45:56
【问题描述】:

我的项目中有一个简单的多对多关系模型。

这是我的课程:

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; }
}

好的,我想在这里实现的是,我想检索所有博客,而不是用户已经拥有的博客。

我可以做相反的事情,即检索特定用户的博客列表,

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();
    }
}

我实际上需要这种方法的反面。例如,假设我的博客表中有 20 个博客。其中 4 个是 User-1 的博客。 (BlogId-1 -> UserId-1 | BlogId-2 -> UserId-1 等...)。

所以,从另一个角度来看,我想向用户 1 展示用户 1 没有的其他 16 个博客。

我希望我确实问清楚了......

感谢您的宝贵时间!

【问题讨论】:

    标签: .net entity-framework linq asp.net-core many-to-many


    【解决方案1】:

    只需否定 where 子句:

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

    【讨论】:

    • 你好克里斯,我试过了,实际上这不是我想要的结果。因为这是多对多的关系,假设如果 User-2 也有相同的博客,那么它也会显示这 4 个博客,但是我确实稍微改变了这个方法,你可以看看吗?它有效,但我不确定这是最好的解决方案......
    【解决方案2】:

    我确实解决了这个问题,将方法更改为这个。但我仍然不确定这是否是最好的解决方案..

    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;               
        }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      • 2011-12-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多