以前(使用 .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 时。我尝试了相同的通用方法,但如果我尝试包含子实体,则会出现以下错误;
属性表达式“x => {from Equipment y in x.Equipment select [y].Type}”无效。该表达式应表示属性访问:“t => t.MyProperty”。有关包含相关数据的更多信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393.
任何人都可以建议我如何解决此问题以将子实体包含在我的通用中Get<T>
Entity Framework Core 2 的方法?
Update
从文档看还有一个额外的include方法
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);
}
尽管我不相信这里的效率,但哪个有效?