【发布时间】: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 导航属性。但包括Apartment、Author和Category应该可以工作。 -
嗨@IvanStoev 感谢您指出这一点。您能否将其作为答案,我想将其标记为答案。谢谢
标签: c# .net entity-framework entity-framework-core