【问题标题】:C# ASP.NET Core Web API include with whereC# ASP.NET Core Web API 包含在 where
【发布时间】:2020-09-23 11:57:33
【问题描述】:

我有这样的代码:

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

在这种状态下工作没有任何问题。

但是当我在我的代码中添加 where 时,当我让它喜欢时

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

所以当我要求 cmets 并回复返回确认 == true 时,我收到以下错误。

错误:在 Include 中使用的 Lambda 表达式无效。

我该如何解决这个问题?

【问题讨论】:

  • 你无法在 include 方法中执行 lambda 表达式
  • 谢谢,我应该如何更改代码?
  • 请不要在图片中发布您的代码,将其作为代码写入您的问题。

标签: c# .net-core entity-framework-core linq-to-entities


【解决方案1】:

恐怕filtered include 仅受 EF Core v5.0.0 支持,目前在 preview 中。

如果您使用的是较旧的 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;

【讨论】:

    【解决方案2】:

    您应该将属性名称作为字符串传递。

    点赞 .Include("Category")

    你可以在这里看到方法的重载:https://docs.microsoft.com/en-us/dotnet/api/system.data.objects.objectquery-1.include?view=netframework-4.8

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-18
      • 1970-01-01
      • 2020-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多