[英]Filtering Data in Many To Many Relationship in Entity Framework
我的項目中有一個簡單的多對多關系模型。
這是我的課程:
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 個博客。
我希望我確實問清楚了...
感謝您的時間!
只需否定 where 子句:
.Where(i => !i.AppUserChasses.Any(a => a.AppUser.Id == user.Id));
我確實解決了這個問題,將方法更改為這個。 但我仍然不確定這是否是最好的解決方案..
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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.