C# 实体框架核心使用包括在QueryType上(数据库视图)
我将EF Core连接到MySql,我有一个名为: 后视 我读到这句话,说我可以对数据库视图使用查询类型 如果我只调用_context.PostViews,它就可以工作,但是如果我在它上使用Include,比如: _context.PostViews.Include(xxxx),它向我抛出以下错误: System.InvalidOperationException:'属性'Comment'不是 实体类型为“PostWithViews”的导航属性。这个 “Include(string)”方法只能与“.”分隔的 导航属性名称。” PostView拥有Post中的所有属性(id、标题、内容、评论等),另外还有一个名为“视图”的列,显示有多少人读过这篇文章C# 实体框架核心使用包括在QueryType上(数据库视图),c#,.net,entity-framework,entity-framework-core,C#,.net,Entity Framework,Entity Framework Core,我将EF Core连接到MySql,我有一个名为: 后视 我读到这句话,说我可以对数据库视图使用查询类型 如果我只调用_context.PostViews,它就可以工作,但是如果我在它上使用Include,比如: _context.PostViews.Include(xxxx),它向我抛出以下错误: System.InvalidOperationException:'属性'Comment'不是 实体类型为“PostWithViews”的导航属性。这个 “Include(string)”方法只能与
这是我的帖子:
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; }
}
以下是我如何包括属性,例如注释:
return GetAll()
.Include(p => p.Author)
.Include(p => p.Comment)
include函数需要一个查询参数,但它仍然不知道其对象,因此需要使用lambda函数传递其对象和所需的参数 试试看:_context.PostView.Include(lambda=>lambda.Comment) 当前(EF Core 2.x)查询类型不支持集合导航属性,如文档主题中所述:
- 它们只能包含指向实体的引用导航属性
Comment
属性看起来像集合导航属性,但对于EF Core,它不是,因此不能在包含/然后包含(或LINQ到实体查询)中使用
但是,公寓
、作者
和类别
都是“指向实体的参考导航属性”,因此它们应该功能齐全。异常消息告诉您问题所在。注释属性的类型是什么?hi@IvanStoev请查看我的更新。hi,请查看。您可能错过了以下要点“它们只能包含指向实体的引用导航属性”。因此,无法将注释
包含在内,因为它是集合导航属性。但是包括公寓
,作者
和类别
应该可以。嗨@IvanStoev谢谢你指出这一点。你能给我一个答案吗?我想把它标为答案。谢谢这对EF Core 3来说也是正确的,对吗?我试图通过执行var people=dbContext.people.Select(p=>new{PersonName=p.Name,Cats=dbContext.AnimalsView.Where(a=>a.Species==“cat”&&a.OwnerID==p.ID}).ToArray())来“伪造”导航属性。但我一个人只有一只猫@Simon_Weaver(1)看起来如此(2)令人惊讶,绝对是一个bug。“动物”实际上是一个没有关键设置的视图(因此不能只使用导航道具)。如果我在循环中“外部”运行它,我会得到c#数组中所有预期的cat,它们都在执行sql的联接中。@Simon_Weaver的确,我的意思是你发现了另一个EF核心bug。事实上,我得到的不仅是一只,而且每个人都有一只和同一只猫!首先(可能)。谁在乎呢,臭虫就是臭虫。
return GetAll()
.Include(p => p.Author)
.Include(p => p.Comment)