EF Core包含在集合类属性上

时间:2018-01-25 17:40:23

标签: c# entity-framework linq .net-core ef-core-2.0

我一直收到像

这样的错误

: The property expression 'met => {from TrM x in met select [x].Tm}' is not valid. The expression should represent a property access: 't => t.MyProperty'.

我有

的班级结构
 public class Tr: BaseModel
{
    public int Id{ get; set; }

    public List<Trm> Mets { get; set; } = new List<Trm>();

    [JsonIgnore]
    public Test TestDef { get; set; }
}



    public class Trm: BaseModel
{

    public Tm tm { get; set; }
}


public class Tm: BaseModel
{

    [JsonIgnore]
    public T TestDef { get; set; }
}

我希望能够说明在加载Tr时加载所有Trm并在加载时包含Tm。

我试过以下

 var results = await _dbContext.Tr
                .Include(tr => tr.Mets ).ThenInclude(met => met.Select(x=> x.tm))
                .Include(tr => tr.TestDef)
                .AsNoTracking()
                .ToListAsync();
            return results;

我该怎么做?

由于

1 个答案:

答案 0 :(得分:4)

您无法在Ef Core中将Select用于Include。您应该使用ThenInclude深入了解加载相关数据。

   var results = await _dbContext.Tr
    .Include(tr => tr.Mets )
         .ThenInclude(met => met.tm)
    .Include(tr => tr.TestDef)
    .AsNoTracking()
    .ToListAsync();

以下是官方documentation