为什么automapper使实体框架插入而不是更新?

时间:2012-02-03 21:21:18

标签: entity-framework automapper poco

我有一个Customers表,其中包含对Addresses表的外部引用。似乎AutoMapper正在做一些让EF认为我的地址引用是新记录而不是更新现有记录的事情。

此代码正确更新地址记录。它没有添加新的:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    updateCustomer.ResellerID = customer.ResellerID;
    updateCustomer.CustomerType = customer.CustomerType;
    updateCustomer.Password = customer.Password;
    updateCustomer.Comments = customer.Comments;

    updateCustomer.Address.ResellerID = customer.Address.ResellerID;
    updateCustomer.Address.AddressCode = customer.Address.AddressCode;
    updateCustomer.Address.AddressType = customer.Address.AddressType;
    updateCustomer.Address.CompanyName = customer.Address.CompanyName;
    updateCustomer.Address.LastName = customer.Address.LastName;
    updateCustomer.Address.FirstName = customer.Address.FirstName;

    uow.SaveChanges();
}

此代码将始终添加新的地址记录:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    Mapper.CreateMap<Customer, Customer>()
        .ForMember(dest => dest.CustomerID, opt => opt.Ignore());
    Mapper.Map(customer, updateCustomer);

    Mapper.CreateMap<Address, Address>()
        .ForMember(dest => dest.ID, opt => opt.Ignore());
    Mapper.Map(customer.Address, updateCustomer.Address);

    uow.SaveChanges();
}

为什么会发生这种情况?

1 个答案:

答案 0 :(得分:1)

我只是想通了。

AutoMapper正在映射Customers中的所有字段,包括Address字段。以下代码非常有用:

using (CSIntUnitOfWork uow = new CSIntUnitOfWork())
{
    CustomerRepository customerRepository = new CustomerRepository(uow, _resellerID);

    DataModels.Customer updateCustomer = customerRepository.GetByID(customer.CustomerID);

    Mapper.CreateMap<Customer, Customer>()
        .ForMember(dest => dest.CustomerID, opt => opt.Ignore())
        .ForMember(dest => dest.Address, opt => opt.Ignore());  // <-- This was the problem!
    Mapper.Map(customer, updateCustomer);

    Mapper.CreateMap<Address, Address>()
        .ForMember(dest => dest.ID, opt => opt.Ignore());
    Mapper.Map(customer.Address, updateCustomer.Address);

    uow.SaveChanges();
}