实体框架核心 3.1 引发"Include has been used on non entity queryable"异常



我有一个基于ASP.NET Core 3.1的项目,我使用实体框架Core 3.1作为ORM。

我有以下两个实体模型

public class PropertyToList
{
public int Id { get; set; }
public int ListId { get; set; } 
public int UserId { get; set; }
public int PropertyId { get; set; }
// ... Other properties removed for the sake of simplicity
public virtual Property Property { get; set; }
}
public class Property
{
public int Id { get; set; }
// ... Other properties removed for the sake of simplicity
public int TypeId { get; set; } 
public int StatusId { get; set; }
public int CityId { get; set; }
public virtual Type Type { get; set; }
public virtual Status Status { get; set; }
public virtual City City { get; set; }
}

我正在尝试查询用户与之相关的所有属性。PropertyToList对象告诉我用户是否与属性相关。以下是我所做的

// I start the query at a relation object
IQueryable<Property> query = DataContext.PropertyToLists.Where(x => x.Selected == true)
.Where(x => x.UserId == userId && x.ListId == listId)
// After identifying the relations that I need,
// I only need to property object "which is a virtual property in" the relation object
.Select(x => x.Property)
// Here I am including relations from the Property virtual property which are virtual properties
// on the Property
.Include(x => x.City)
.Include(x => x.Type)
.Include(x => x.Status);
List<Property> properties = await query.ToListAsync();

但那个代码抛出了这个错误

Include已用于非实体可查询

是什么原因导致了此问题?我该怎么修?

将include放在引用父实体之后。您也可以执行TheInInclude来带来所包含实体的子实体。你需要为每个TheInInclude做一个Include。

然后,您可以在包含/筛选后进行选择。类似于:

var query = DataContext.PropertyToLists
.Include(p => p.Property).ThenInclude(p => p.City)
.Include(p => p.Property).ThenInclude(p => p.Type)
.Include(p => p.Property).ThenInclude(p => p.Status)
.Where(p => p.Selected == true && p.UserId == userId && p.ListId == listId)
.Select(p => p.Property);

观察到,您的域模型PropertyToList和Property都具有虚拟属性。除此之外,您还可以使用Include运算符来选择这些特性。

这是不必要的,当用virtual定义属性时,它将被延迟加载。因此不需要Include。延迟加载不是推荐的方式,使用include更好,因此您只能选择所需的图形属性。

相关内容

最新更新