c# - Entity Framework 嵌套导航属性仅计数

标签 c# .net entity-framework navigation-properties

我有三个模型类

public class Item1{

    public int Id;

    public List<Item2> Item2List { get; set; }
}

public class Item2{
    public int Id;

    //this is the FK
    public int Item1Id {get;set;}

    public Item1 Item1 {get;set;}

    //Not in db. Ignored field in EntityTypeConfiguration
    public int Item3Count;

    public List<Item3> Item3List { get; set; }
}

public class Item3{
    public int Id;

    //this is the FK
    public int Item2Id {get;set;}

    public Item2 Item2 {get;set;}    
}

我想返回 Item1 的列表以及关联的 Item2 的列表,并在不加载 Item3List 的情况下加载与 Item2 关联的 Item3List 的 COUNT。

这是我现在正在做的事情:

public IEnumerable<Item1> GetItems()
{
    return base.Query().Include(item1 => item1.Item2List.Select(item2 => item2.Item3List)).ToList();
}

这会返回所有 3 个对象 Item1、Item2 和 Item3 的列表。但我只需要 Item3Count 中 Item3List 的计数,而不是整个 Item3List 列表。我怎样才能做到这一点?我在下面尝试了这个,但它抛出了错误。

return base.Query().Include(item1 => item1.Item2List.Select(item2 => new Item2 {
Item3Count = item2.Item3List.Count()
})).ToList();

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

最佳答案

你想要的是不可能的。当然,您不能在 EF LINQ 查询中填充未映射的属性,因为这是不映射它的想法。但你已经知道了。

你真正想做的是这样的:

context.Item1s.Select(item1 => new Item1
{
    Id = item1.Id,
    Item2s = item1.Item2List.Select(item2 => new Item2List
    {
        Id = item2.Id,
        Item3Count = item2.Item3List.Count()
    })
})

但是 EF 不允许您在 EF 查询中构造实体对象。

替代品没有吸引力。

你可以构建一个匿名类型的结构......

context.Item1s.Select(item1 => new
{
    Item1 = item1,
    Item2s = item1.Item2List.Select(item2 => new
    {
        Item2 = item2,
        Item3Count = item2.Item3List.Count()
    })
})

... 并使用它来构造一个 Item1 对象的列表,每个对象都有它们的 Item2Lists of Item2s with Item3Count 值。

更好但仍不接近理想的是使用 AutoMapper 并将实体映射到 DTO:

Mapper.CreateMap<Item1,Item1Dto>();
Mapper.CreateMap<Item2,Item2Dto>();

您可以使用 AutoMapper 的 flattening feature填充 Item3Count。为此,Item2Dto 应该有一个属性 Item3ListCount,AutoMapper 会将其转换为 Item3List.Count()

关于c# - Entity Framework 嵌套导航属性仅计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079953/

相关文章:

c# - WPF C# 应用程序中的哈希密码

c# - 为什么我不能获得独占锁?

c# - 如何从单独的 C# 项目调用 VSTO AddIn 方法?

.net - 使用触发器更改 SolidcolorBrush 资源的颜色?

.net - 如何告诉 Entity Framework View 中的列可以为空?

c# - 无法使用 PRISM 5、MVVM 和 EF 6 在 WPF 中刷新 DataGrid

c# - 我在 Mysql 中遇到希伯来语问题。我与 Visualstudio10、连接器和 linq 一起使用。我能做些什么?

c# - 在 winforms 的 tabControl 中隐藏选项卡标题

c# - 如何检查模型列表中的重复条目?

.net - 平衡的树状数据结构,可调整为素数大小