Automapper和Base类

时间:2015-10-09 13:23:23

标签: .net inheritance

首先让我说我是自动映射器的新手。我有一个基类,其类包含继承基类,如下所示:

public abstract class Base
{
    [Required]
    public Guid CreatedBy { get; set; }
    [Required]
    public DateTime DateCreated { get; set; }
    [Required]
    public DateTimeOffset DateCreatedOffset { get; set; }
    public Guid? UpdatedBy { get; set; }
    public DateTime? DateUpdated { get; set; }
    public DateTimeOffset? DateUpdatedOffset { get; set; }
    [Required]
    public bool Deleted { get; set; }
}

public class Customer : Base
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid CustomerId { get; set; }

    [Required]
    public Guid CompanyId { get; set; }
    public virtual Company Company { get; set; }

    [Required]
    public TypeCustomer CustomerType { get; set; }

    [Display(Name = "Customer Name")]
    public string CustomerName { get; set; }

    [StringLength(20)]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(20)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [DataType(DataType.EmailAddress)]
    public string PrimaryEmail { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<PhoneNumber> PhoneNumbers { get; set; }
}
要映射的

类如下:

public class CustomerObject
{
    public Guid CustomerId { get; set; }
    public Guid CompanyId { get; set; }
    public Guid CreatedBy { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTimeOffset DateCreatedOffset { get; set; }
    public Guid UpdatedBy { get; set; }
    public DateTime? DateUpdated { get; set; }
    public DateTimeOffset? DateUpdatedOffset { get; set; }
    public TypeCustomer CustomerType { get; set; }
    public string CustomerName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    [DataType(DataType.EmailAddress)]
    public string PrimaryEmail { get; set; }

    public virtual ICollection<AddressObject> Addresses { get; set; }
    public virtual ICollection<PhoneNumberObject> PhoneNumbers { get; set; }
}

映射类的代码:

    Customer customer = GetCustomerById(customerObject.CustomerId);
    Mapper.CreateMap<CustomerObject, Customer>();
    customer = Mapper.Map<CustomerObject, Customer>(customerObject);
    customer.UpdatedBy = userId;
    customer.DateUpdated = DateTime.UtcNow;
    customer.DateUpdatedOffset = DateTimeOffset.UtcNow;

当尝试将客户类的实例映射到客户对象时,我将丢失基类中的所有属性。有人碰到这个吗?

1 个答案:

答案 0 :(得分:0)

您使用的是哪个版本的AutpMapper?我假设您正在使用nuget包的最新版本4.0.4

如果是,则此功能已存在于automapper中,此处为fiddle demonstrating that