I have a Customers table with a foreign reference to the Addresses table. It appears that AutoMapper is doing something to make EF think that my Address reference is a new record rather than updating the existing record.
This code updates the Address record correctly. It does not add a new one:
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();
}
This code will always add a new Address record:
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();
}
Any ideas why this is happening?
I just figured it out.
AutoMapper is mapping ALL the fields in Customers, including the Address field. The following code works great: