简体   繁体   中英

Automapper not mapping a computed property

I have a simple interface like:

interface IEntity
{
    int EntityID { get; }
}

and a number of classes implementing using a computed property for the EntityID , like so:

class Person : IEntity
{
    public int PersonID { get; set; }
    public int EntityID => PersonID;
}

I'm trying to map to another class with the same property, like the one below, using Automapper:

class Result
{
    public int EntityID { get; }
}

I can't get it to map the property though. The test below fails because the EntityID in the result is always 0 , even when I explicitly set the ForMember() mapping, like below:

using AutoMapper;
using Xunit;

public class UnitTest1
{       
    [Fact]
    public void Test1()
    {
        var mapper = new MapperConfiguration(cfg => cfg.CreateMap<IEntity, Result>()
        .ForMember(dest => dest.EntityID, i => i.MapFrom(src => src.EntityID)))
            .CreateMapper();

        var result = mapper.Map<Result>(new Person() { PersonID = 5 });
        Assert.Equal(5, result.EntityID);
    }
}

There has got to be some obvious solution I'm missing here. Any help would be appreciated.

对于简单的属性,AM 需要一个 setter 来工作,就像手动方法一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM