0

这是我的模型层次结构:

public interface INodeModel<T> : INodeModel
where T : struct
{
    new T? ID { get; set; }
}

public interface INodeModel
{
    object ID { get; set; }
    string Name { get; set; }
}

public class NodeModel<T> : INodeModel<T>
 where T : struct
{
    public T? ID { get; set; }
    public string Name { get; set; }

    object INodeModel.ID
    {
        get
        {
            return ID;
        }

        set
        {
            ID = value as T?;
        }
    }
}

public class NodeDto<T> where T : struct
{
    public T? ID { get; set; }
    public string Name { get; set; }
}

这些是我的映射和测试:

    class Program
{
    private static MapperConfiguration _mapperConfiguration;

    static void Main(string[] args)
    {
        _mapperConfiguration = new MapperConfiguration(cfg =>
        {

            cfg.CreateMap(typeof(NodeDto<>), typeof(NodeModel<>));
            cfg.CreateMap(typeof(NodeDto<>), typeof(INodeModel<>));
            cfg.CreateMap(typeof(INodeModel<>), typeof(NodeModel<>));

        });

        var dto = new NodeDto<int> { ID = 1, Name = "Hi" };

        var obj = _mapperConfiguration.CreateMapper().Map<INodeModel<int>>(dto);


        Console.Write(obj.ID);
        Console.ReadLine();
    }
}

这是例外:

AutoMapper.AutoMapperMappingException:

映射类型:

NodeDto 1 -> INodeModel1 NodeDto`1[[System.Int32] ->

INodeModel`1[[System.Int32]

信息:

接口具有冲突的属性 ID 参数名称:interfaceType

堆:

在 AutoMapper.Internal.ProxyGenerator。CreateProxyType(类型接口类型)

在 AutoMapper.Internal.ProxyGenerator。GetProxyType(类型接口类型)

在 AutoMapper.MappingEngine。CreateObject(ResolutionContext 上下文)

4

1 回答 1

1

AutoMapper 在创建代理实现时感到困惑,您的接口中有两个同名成员。您正在使用阴影,这更加困难。而不是假设 AutoMapper 可以理解这一点,祝你好运向新团队成员解释,我宁愿明确接口类实现:

cfg.CreateMap(typeof(NodeDto<>), typeof(NodeModel<>));
cfg.CreateMap(typeof(NodeDto<>), typeof(INodeModel<>))
    .ConvertUsing(typeof(NodeModelConverter<>));
cfg.CreateMap(typeof(INodeModel<>), typeof(NodeModel<>));

public class NodeModelConverter<T> :
    ITypeConverter<NodeModel<T>, INodeModel<T>> where T : struct
{
    public INodeModel<T> Convert(NodeModel<T> source, ResolutionContext context)
         => new NodeModelImpl {ID = source.ID, Name = source.Name};

    private class NodeModelImpl : INodeModel<T>
    {
        public T? ID { get; set; }

        public string Name { get; set; }

        object INodeModel.ID
        {
            get { return ID; }

            set { ID = (T?) value; }
        }
    }
}

没有魔法,完全明确和明显!

于 2016-06-20T17:34:54.497 回答