Suneth
Suneth

Reputation: 31

Automapper Project.To Null reference exception

I am trying to use the Automapper QueryableExtensions to project an EF based entity into a dto that involves a custom resolver. It fails with a NRE in AutoMapper.PropertyMap.ResolveExpression. I've traced the code and it fails because the CustomExpression in the PropertyMap class is null.

I can easily reproduce this with a simple in memory collection as given below (although I understand that Project.To is meant to be used with a backed LINQ provider).

here's the sample code...am I missing something obvious?

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();
    }     
}
}

Upvotes: 1

Views: 2275

Answers (2)

Jimmy Bogard
Jimmy Bogard

Reputation: 26785

This scenario is not supported by LINQ providers, and so not supported by AutoMapper. See this for more details:

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

See also this issue : https://github.com/AutoMapper/AutoMapper/issues/362

In particular, custom value resolvers can't be used by LINQ providers. Instead, take a look at MapFrom.

Upvotes: 6

Rob West
Rob West

Reputation: 5241

I'm not sure if it is just a typo but shouldn't you have a type in the ResolveUsing call? So it should be:

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

Upvotes: 0

Related Questions