【问题标题】:Automapper Project.To Null reference exceptionAutomapper Project.To Null 引用异常
【发布时间】:2014-01-06 11:17:09
【问题描述】:

我正在尝试使用 Automapper QueryableExtensions 将基于 EF 的实体投影到涉及自定义解析器的 dto 中。 AutoMapper.PropertyMap.ResolveExpression 中出现 NRE 失败。我跟踪了代码,但它失败了,因为 PropertyMap 类中的 CustomExpression 为空。

我可以使用下面给出的简单内存集合轻松重现这一点(尽管我知道 Project.To 旨在与支持的 LINQ 提供程序一起使用)。

这是示例代码...我是否遗漏了一些明显的东西?

public class Contract
    {
    public string ContractNumber { get; set; }
    public DateTime SettlementDateTime { get; set; }
    }

    public class ContractDto
    {
    public Settlement Settlement { get; set; }
    }

    public class Settlement
    {
    public string DeliveryLocation { get; set; }
    public DateTime SettlementDateTime { get; set; }
    }

    public class ContractProfile : Profile
    {
    protected override void Configure()
    {
    IMappingExpression map = Mapper.CreateMap();
    map.ForAllMembers(opts => opts.Ignore());
    map.ForMember(v => v.Settlement, opts => opts.ResolveUsing());
    }

    }
public class SettlementCustomResolver:ValueResolver
{
protected override Settlement ResolveCore(Contract source)
{
return new Settlement() { DeliveryLocation = string.Empty, SettlementDateTime = source.SettlementDateTime };
}
}

internal class Program
{

    private static void Main(string[] args)
    {
        ConfigureAutoMapper();
        var contracts = new[]
                        {
                            new Contract { ContractNumber = "123", SettlementDateTime = DateTime.Today.AddDays(-1) },
                            new Contract { ContractNumber = "124", SettlementDateTime = DateTime.Today.AddDays(-2) }
                        };

        //Exception happens on the following line...
        var contractDtos = contracts.AsQueryable().Project().To<ContractDto>();

        Console.Read();
    }

    private static void ConfigureAutoMapper(){

        Mapper.AddProfile<ContractProfile>();
        Mapper.AssertConfigurationIsValid();
    }     
}
}

【问题讨论】:

    标签: automapper nullreferenceexception


    【解决方案1】:

    LINQ 提供程序不支持这种情况,因此 AutoMapper 也不支持。有关详细信息,请参阅此内容:

    https://github.com/AutoMapper/AutoMapper/wiki/Queryable-Extensions

    另请参阅此问题:https://github.com/AutoMapper/AutoMapper/issues/362

    特别是,LINQ 提供程序不能使用自定义值解析器。相反,请查看 MapFrom。

    【讨论】:

      【解决方案2】:

      我不确定这是否只是一个错字,但您不应该在 ResolveUsing 调用中有一个类型吗?所以应该是:

      map.ForMember(v => v.Settlement, opts => opts.ResolveUsing<SettlementCustomResolver>());
      

      【讨论】:

        猜你喜欢
        • 2022-06-25
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 2019-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多