为什么投影不包括 EF Core 2.0 中的导航嵌套属性?
Why projection is not including navigation nested properties in EF Core 2.0?
我有这些类型
public class Model
{
public string Name { get; set; }
public virtual List<Nested> Nested { get; set; }
}
public class Nested
{
public Guid ModelId { get; set; }
public virtual Model Model{ get; set; }
public Guid FurtherNestedId{ get; set; }
public virtual FurtherNested FurtherNested { get; set; }
}
public class FurtherNested
{
public Guid Id {get; set;}
public string Name{ get; set; }
}
我正在尝试使用这些来构建视图模型,如下所示:
_dbContext.Models.Include(x => x.Nested).ThenInclude(x => x.FurtherNested).Select(x => new {
Nested= x.Nested
}).ToList();
出于某种原因,这会创建一个具有嵌套属性的对象列表(如预期的那样),但是列表项的嵌套 属性 设置了 FurtherNestedId 但没有设置 FurtherNested,因此我无法获得 FurtherNested.Name。 IE FurtherNestedId 存在,但实际导航 属性 不存在。
但我的数据上下文包含...
请问这是为什么?
编辑:还值得注意的是,通过将 toList() 向上移动到 .Select() 之上,我得到了我想要的,但执行时间是原来的 3 倍。
编辑:我想得到这样的东西:
{
any other properties that live on Model,
Nested: [
furtherNestedId: '',
furtherNested: { Name: '' }
]
}
Include doesn't work with projection queries. Once you start projecting (Select), you need to continue with Select all the way down.
所以试试这个:
var myModels = _dbContext.Models.Include(x => x.Nested).ThenInclude(n => n.FurtherNested).Select(x => new
{
Name = x.Name,
Nested = x.Nested.Select(n => new
{
FurtherNestedId = n.FurtherNestedId,
FurtherNested = n.FurtherNested
})
}).ToList();
希望对您有所帮助。
我有这些类型
public class Model
{
public string Name { get; set; }
public virtual List<Nested> Nested { get; set; }
}
public class Nested
{
public Guid ModelId { get; set; }
public virtual Model Model{ get; set; }
public Guid FurtherNestedId{ get; set; }
public virtual FurtherNested FurtherNested { get; set; }
}
public class FurtherNested
{
public Guid Id {get; set;}
public string Name{ get; set; }
}
我正在尝试使用这些来构建视图模型,如下所示:
_dbContext.Models.Include(x => x.Nested).ThenInclude(x => x.FurtherNested).Select(x => new {
Nested= x.Nested
}).ToList();
出于某种原因,这会创建一个具有嵌套属性的对象列表(如预期的那样),但是列表项的嵌套 属性 设置了 FurtherNestedId 但没有设置 FurtherNested,因此我无法获得 FurtherNested.Name。 IE FurtherNestedId 存在,但实际导航 属性 不存在。
但我的数据上下文包含...
请问这是为什么?
编辑:还值得注意的是,通过将 toList() 向上移动到 .Select() 之上,我得到了我想要的,但执行时间是原来的 3 倍。
编辑:我想得到这样的东西:
{
any other properties that live on Model,
Nested: [
furtherNestedId: '',
furtherNested: { Name: '' }
]
}
Include doesn't work with projection queries. Once you start projecting (Select), you need to continue with Select all the way down.
所以试试这个:
var myModels = _dbContext.Models.Include(x => x.Nested).ThenInclude(n => n.FurtherNested).Select(x => new
{
Name = x.Name,
Nested = x.Nested.Select(n => new
{
FurtherNestedId = n.FurtherNestedId,
FurtherNested = n.FurtherNested
})
}).ToList();
希望对您有所帮助。