【问题标题】:Entity Framework Core Use Include on QueryType(Database View)Entity Framework Core Use Include on QueryType(数据库视图)
【发布时间】:2019-05-14 19:18:14
【问题描述】:

我已将 EF Core 连接到 MySql,并且我有一个名为:

帖子视图

我读到这个article 说我可以将查询类型用于数据库视图。

如果我只调用 _context.PostViews,它就可以工作,但如果我像这样使用 Include:

_context.PostViews.Include(xxxx),它会抛出这个错误:

System.InvalidOperationException: '属性 'Comment' 不是 实体类型“PostWithViews”的导航属性。这 'Include(string)' 方法只能与 '.' 一起使用分开的清单 导航属性名称。'

PostView 拥有 Post 中的所有属性(id、title、content、Comment 等),此外它还有一个名为:Views 的额外列,显示有多少人阅读了这篇文章。


这是我的帖子:

public partial class Post
    {
        public Post()
        {
            Comment = new HashSet<Comment>();
        }

        public string Id { get; set; }
        public string ApartmentId { get; set; }
        public string AuthorId { get; set; }
        public string CategoryId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime? DueDate { get; set; }
        public bool? Disabled { get; set; }
        public DateTime? CreatedAt { get; set; }
        public DateTime? UpdatedAt { get; set; }
        public string UpdatedBy { get; set; }

        public virtual Apartment Apartment { get; set; }
        public virtual User Author { get; set; }
        public virtual PostCategory Category { get; set; }}
        public virtual ICollection<Comment> Comment { get; set; }
    }

PostWithViews 类与 Post 几乎相同,但多了 1 个属性 Views:

public int Views { get; set; }

这是我包含属性的方式,例如评论:

return GetAll()
       .Include(p => p.Author)
       .Include(p => p.Comment)

【问题讨论】:

  • 异常消息告诉你问题。 Comment 属性的类型是什么?
  • 嗨@IvanStoev,请查看我的更新。
  • 嗨,看看Compare query types to entity types。您可能错过了以下项目符号“它们只能包含指向实体的引用导航属性。”。所以没有办法让 Comment 包含在内,因为它是一个 collection 导航属性。但包括ApartmentAuthorCategory 应该可以工作。
  • 嗨@IvanStoev 感谢您指出这一点。您能否将其作为答案,我想将其标记为答案。谢谢

标签: c# .net entity-framework entity-framework-core


【解决方案1】:

目前 (EF Core 2.x) 查询类型不支持 集合导航属性,如 Compare query types to entity types 文档主题中所述:

  • 它们只能包含指向实体的参考导航属性。

因此,尽管您的 Comment 属性看起来像集合导航属性,但对于 EF Core 却不是,因此不能在 Include / ThenInclude(或 LINQ to Entities 查询)中使用。

但是ApartmentAuthorCategory“指向实体的引用导航属性”,因此它们应该是功能齐全的。

【讨论】:

  • 所以 EF Core 3 也是如此,对吧?我试图通过var people = dbContext.People.Select(p =&gt; new { PersonName = p.Name, Cats = dbContext.AnimalsView.Where(a =&gt; a.Species == "cat" &amp;&amp; a.OwnerID == p.ID }).ToArray() }) 来“伪造”一个导航属性。但我每人只能养一只猫!
  • @Simon_Weaver (1) 看起来是这样 (2) 非常令人惊讶,绝对是一个错误。
  • ‘Animals’实际上是一个没有键集的视图(因此不能只使用导航道具)。如果我在循环中“外部”运行它,我会在 c# 数组中获得所有预期的猫,并且它们都在执行的 sql 的连接中。
  • @Simon_Weaver 确实,我的意思是您发现了另一个 EF Core 错误。实际上,我得到的不仅是一只,而且每个人都有一只相同的猫!
  • 第一(可能)。谁在乎,bug 就是 bug。
【解决方案2】:

一个包含函数需要一个查询参数,但它仍然不知道它的对象,所以你需要使用一个 lambda 函数来传递它的对象和你想要的参数

试试看:_context.PostView.Include(lambda => lambda.Comment);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多