具有通用类型继承的AutoMapper

时间:2009-12-01 04:11:42

标签: c# automapper

我正在尝试使用AutoMapper将CustomerDTO映射到我的域实体ICustomer。一切都适用于第一个继承级别,但不适用于其他级别。

我正在为我的域模型使用Interfaces,因为StructureMap从我的LinqToSql Database Infrastructure层注入了具体的类型。

public interface IBaseEntity<TPk>
{
    TPk Id { get; }
}

public interface ICustomer : IBaseEntity<int>
{
    string Email { get; set; }
}

[DataContract]
public class CustomerDTO
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Email { get; set; }
}

现在是AutoMapper映射

Mapper.CreateMap<CustomerDTO, ICustomer>();

Mapper.CreateMap<ICustomer, CustomerDTO>();

Mapper.AssertConfigurationIsValid();

现在我正在使用映射

    public CreateCustomerServiceResult CreateCustomer(CustomerDTO customer)
    {
        var result = new CreateCustomerServiceResult();
        try
        {
            var originalMapped = Mapper.DynamicMap<CustomerDTO, ICustomer>(customer);

            var newCustomer = _customerService.CreateCustomer(originalMapped);

            var newMapped = Mapper.DynamicMap<ICustomer, CustomerDTO>(newCustomer);

            result.Customer = newMapped;
        }
        catch (Exception ex)
        {

        }
        return result;
    }

我在“Id”属性上有 Dictionnary缺少Key Exception ...

1 个答案:

答案 0 :(得分:1)

知道了!

问题是由于缺少IBaseEntity的“Id”属性。

更改后一切正常

public interface IBaseEntity<TPk>
{
    TPk Id { get; set; }
}