gpt4 book ai didi

c# - .ThenInclude 用于 Entity Framework Core 2 中的子实体

转载 作者:太空宇宙 更新时间:2023-11-03 22:45:32 35 4
gpt4 key购买 nike

以前(使用 .net 4.5.2 和 EF 6 时)。我有一个通用的 Get接受多个包含的方法如下;

public abstract class DataContext : IdentityDbContext<ApplicationUser, ApplicationRole, int>, IDataContext
{
public DataContext(DbContextOptions options)
: base(options)
{
}

// reduced for brevity

public T Get<T>(int id, params Expression<Func<T, object>>[] includes) where T : class, IEntity
{
return this.Set<T>().Include(includes).FirstOrDefault(x => x.Id == id);
}

然后我会调用例如;

context.Get<Job>(id, 
x => x.Equipment,
x => x.Equipment.Select(y => y.Type));

包括Job.Equipment还有 Job.Equipment.Type .

但是,当我将其移植到 asp.net core 2 时。我尝试了相同的通用方法,但如果我尝试包含子实体,则会出现以下错误;

The property expression 'x => {from Equipment y in x.Equipment select [y].Type}' is not valid. The expression should represent a property access: 't => t.MyProperty'. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

谁能建议我如何解决这个问题以在我的通用 Get<T> 中包含子实体?使用 Entity Framework Core 2 的方法?

更新

从文档来看还有一个额外的包含方法

include(string navigationPropertyPath)

我添加了以下方法;

    public T Get<T>(int id, string[] includes) where T : class, IEntity
{
var result = this.Set<T>().AsQueryable();

foreach(var include in includes)
{
result = result.Include(include);
}

return result.FirstOrDefault(x => x.Id == id);
}

哪个行得通,尽管我不相信这里的效率?

最佳答案

EF 核心 Include/ThenInclude模式不能用 Expression<Func<T, object>>[] 表示就像在 EF6 中一样。

查看其中一个 EF Core 扩展的源代码 - Microsoft.EntityFrameworkCore.UnitOfWork ,它声称是

A plugin for Microsoft.EntityFrameworkCore to support repository, unit of work patterns, and multiple database with distributed transaction supported.

看起来包含的预期模式应该基于 Func<IQueryable<T>, IIncludableQueryable<T, object>> :

public T Get<T>(int id, Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null) where T : class, IEntity
{
var result = this.Set<T>().AsQueryable();

if (include != null)
result = include(result);

return result.FirstOrDefault(x => x.Id == id);
}

缺点是它增加了对调用者的 EF Core 依赖并且需要 using Microsoft.EntityFrameworkCore; .在您的情况下,这不是必需的,因为您正在扩展 DbContext .

您的示例的用法是:

context.Get<Job>(id, q => q
.Include(x => x.Equipment)
.ThenInclude(y => y.Type));

关于c# - .ThenInclude 用于 Entity Framework Core 2 中的子实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50137839/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com