我有一个 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();
}
知道为什么会这样吗?
最佳答案
我刚刚想通了。
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();
}
关于entity-framework - 为什么 automapper 使 Entity Framework 插入而不是更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9135655/