我有一个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();
}
为什么会发生这种情况?
答案 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();
}