【问题标题】:AutoMapper: How to map between Linq Expressions (Func<>)AutoMapper:如何在 Linq 表达式之间进行映射 (Func<>)
【发布时间】:2018-07-10 12:25:52
【问题描述】:

我正在使用存储库模式,所以我的存储库只知道 DTO。它必须使用实体框架通过一些过滤器查询数据库。 我的问题是 Entity Framework 只知道 DB 模型类,所以我必须“自动映射”Expression,然后才能在任何查询中使用它们。

我已经声明了一个接受 Expression 作为过滤器的方法。

public interface IRepository
{
    IEnumerable<ItemDTO> GetItemsWithFilter(Expression<Func<ItemDTO, bool>> filter)
    {
        var filterDb = Mapper.Map<Expression<Func<ItemDB, bool>>>(filter);
        return dbContext.CONFIGURATIONS.Where(filterDb).Select(x => Mapper.Map<ItemDTO>(x));
    }
}

public class ItemDTO
{
   public int numero { get; set; }
   public string name { get; set; }
} 

public class ItemDB //they are both the same, just for testing purpose
{
   public int numero { get; set; }
   public string name { get; set; }
}

//failing code 
 Repository.GetItemsWithFilter(x => x.name=="a");

我关注了tutorial,说可以在表达式之间进行映射,但我遇到了一些错误:

“LINQ to Entities 不支持指定的类型成员‘name’。仅支持初始化程序、实体成员和实体导航属性。”}

【问题讨论】:

标签: entity-framework expression automapper


【解决方案1】:

我通过包含这个扩展方法调用解决了这个问题:

 Mapper.Initialize(cfg => {
    cfg.AddExpressionMapping();
    // Rest of your configuration
 });

记得安装nuget包AutoMapper.Extensions.ExpressionMapping

Install-Package AutoMapper.Extensions.ExpressionMapping

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多