Automapper ignore readonly properties

2019-07-03 04:43发布

问题:

I'm trying to map from one object to another that has a public readonly Guid Id, which I want to ignore. I have tried like this:

Mapper.CreateMap<SearchQuery, GetPersonsQuery>()
              .ForMember(dto => dto.Id, opt => opt.Ignore());

This seems to fail because Id is readonly:

AutoMapperTests.IsValidConfiguration threw exception: 
System.ArgumentException: Expression must be writeable

Is there any way around this?

回答1:

I don't think ReadOnly fields are supported by AutoMapper. Only way I could get it to work was to wrap the readonly field with a property with only a getter:

class Program
{
    static void Main()
    {
        Mapper.CreateMap<SearchQuery, GetPersonsQuery>();

        var source = new SearchQuery {Id = Guid.NewGuid(), Text = Guid.NewGuid().ToString() };

        Console.WriteLine("Src: id = {0} text = {1}", source.Id, source.Text);

        var target = Mapper.Map<SearchQuery, GetPersonsQuery>(source);

        Console.WriteLine("Tgt: id = {0} text = {1}", target.Id, target.Text);

        Console.ReadLine();
    }
}

internal class GetPersonsQuery
{
    private readonly Guid _id = new Guid("11111111-97b9-4db4-920d-2c41da24eb71");

    public Guid Id { get { return _id; } }
    public string Text { get; set; }
}

internal class SearchQuery
{
    public Guid Id { get; set; }
    public string Text { get; set; }
}