如何解决C#ASP.NET Core Web API包含在何处
我有这样的代码:
public Blog GetBlogWithCategoryTagsAndCommentsWithReplies(int id)
{
return _context.Blogs
.Where(blog => blog.Id == id)
.Include(blog => blog.Category)
.Include(blog => blog.BlogTags)
.ThenInclude(blogtag => blogtag.Tag)
.Include(blog => blog.Comments)
.ThenInclude(comment => comment.User)
.Include(blog => blog.Comments)
.ThenInclude(comment => comment.Replies)
.ThenInclude(reply => reply.User)
.FirstOrDefault();
}
在这种状态下可以正常工作。
但是当我在代码中添加位置时,就像这样
public Blog GetBlogWithCategoryTagsAndCommentsWithReplies(int id)
{
return _context.Blogs
.Where(blog => blog.Id == id)
.Include(blog => blog.Category)
.Include(blog => blog.BlogTags)
.ThenInclude(blogtag => blogtag.Tag)
.Include(blog => blog.Comments.Where(comment=>comment.Confirmation==true))
.ThenInclude(comment => comment.User)
.Include(blog => blog.Comments)
.ThenInclude(comment => comment.Replies.Where(reply=>reply.Confirmation==true))
.ThenInclude(reply => reply.User)
.FirstOrDefault();
}
因此,当我要求评论并回复以返回确认== true时,会出现以下错误。
错误:在Include中使用的Lambda表达式无效。
如何解决此问题?
解决方法
您应该将属性名称作为字符串传递。
就像.Include(“ Category”)
您可以在这里看到该方法的重载:https://docs.microsoft.com/en-us/dotnet/api/system.data.objects.objectquery-1.include?view=netframework-4.8
,恐怕目前preview
中的EF Core v5.0.0仅支持filtered include。
如果您使用的是旧版EF Core,则可以从this thread中查看一些想法。
例如,如果您可以承受拉动所有内容和在内存中进行过滤的性能影响,则可以尝试执行以下操作:
var blog = _context.Blogs
.Where(blog => blog.Id == id)
.Include(blog => blog.Category)
.Include(blog => blog.BlogTags)
.ThenInclude(blogtag => blogtag.Tag)
.Include(blog => blog.Comments)
.ThenInclude(comment => comment.User)
.Include(blog => blog.Comments)
.ThenInclude(comment => comment.Replies)
.ThenInclude(reply => reply.User)
.FirstOrDefault();
blog.Comments = blog.Comments.Where(comment => comment.Confirmation == true).ToList();
foreach(var comment in blog.Comments)
{
comment.Replies = comment.Replies.Where(reply => reply.Confirmation == true).ToList();
}
return blog;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。