【发布时间】:2012-02-03 21:21:17
【问题描述】:
我有一个客户表,其中包含对地址表的外部引用。看来 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();
}
任何想法为什么会发生这种情况?
【问题讨论】:
标签: entity-framework automapper poco