Automapper Project.To Null引用异常

时间:2013-12-18 10:20:57

标签: automapper nullreferenceexception

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

我可以使用下面给出的简单内存集合轻松地重现这一点(虽然我知道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();
    }     
}
}

2 个答案:

答案 0 :(得分:5)

LINQ提供程序不支持此方案,因此AutoMapper不支持此方案。有关详细信息,请参阅此处:

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

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

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

答案 1 :(得分:0)

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

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