Entity Framework Core 3.1 抛出了“Include has been used on non entity queryable”异常。

8

我有一个基于ASP.NET Core 3.1的项目,其中使用Entity Framework 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

可能是什么原因导致了这个问题?我该如何解决?

2个回答

12

在引用父实体后立即放置您的include。您可以使用ThenInclude来获取包含实体的子实体。每个ThenInclude都需要进行一次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);

谢谢。在EF 6中,这实际上是相反的,为了避免一些错误,你必须把它们放在最后。 - Romain Vergnory

1
观察发现,你的领域模型PropertyToList和Property都有虚拟属性。此外,你正在使用Include运算符来选择这些属性。
这是不必要的,当属性被定义为虚拟时,它将被延迟加载。因此,不需要Include。延迟加载不是推荐的方式,使用include更好,这样你只选择所需的图形属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接