EF Core / .NET 6. 使用表达式在实体上选择

问题描述 投票:0回答:2

我正在尝试使用表达式实现

Select
,以将对象保持为 IQueryable 并选择到子导航集合中

示例代码:

public Expression<Func<Item, ItemModel>> MapToModel =>
        Ent => new ItemModel
        {
            Id = Ent.Id,
            Name = Ent.Name,
            SKU = Ent.SKU,
            Variations = Ent.Variations == null ? default : Ent.Variations.Select(this.VariationMapper),
        };

VariationMapper 如下:

public Expression<Func<ItemVariation, VariationModel>> VariationMapper =>
        Ent => new VariationModel()
        {
            Id = Ent.Id,
            Name = Ent.Name,
        };

但是我收到以下错误:

“ICollection”不包含“Select”的定义,并且最佳扩展方法重载“Queryable.Select(IQueryable, Expression>)”需要“IQueryable”类型的接收器

我对如何解决这个问题有点困惑。或者如果这可能的话。该子属性的类型为

ICollection<T>
,因为它是导航属性。

c# generics entity-framework-core iqueryable
2个回答
1
投票

尝试使用

AsQueryable

Variations = Ent.Variations == null 
    ? default 
    : Ent.Variations
         .AsQueryable()
         .Select(this.VariationMapper)
         .ToList()

1
投票

您不需要检查集合中的

null
,EF Core 将处理它。此外,EF Core 将无法正确翻译您的映射器。它需要扩展,这是由 LINQKit 提供的。

public Expression<Func<Item, ItemModel>> MapToModel =>
        Ent => new ItemModel
        {
            Id = Ent.Id,
            Name = Ent.Name,
            SKU = Ent.SKU,
            Variations = Ent.Variations.Select(this.VariationMapper.Expand()),
        };

如何激活 LINQKit,您可以在此 answer 中找到,以及如何创建可重用

AsDto
方法的示例。

© www.soinside.com 2019 - 2024. All rights reserved.