When I execute the code below, in address on Mapper.Map line it’s ok I have the right values coming from the model but the customer.Address, an ISet collection, is not updated on session.Save(customer) line. Should be updated since address is a reference.
public ActionResult SaveAddressInvoice(CustomerAddressForView model)
{
var tx = session.BeginTransaction();
var customer = session.Get<Customer>(customerId);
var address = customer.Address.Where(x => x.Id == myAddressId).First<CustomerAddress>();
address = Mapper.Map<CustomerAddressForView, CustomerAddress>(model);
session.Save(customer);
tx.Commit();
}
If I do:
var address = customer.Address.Where(x => x.Id == myAddressId).First<CustomerAddress>();
address.Street = "MyStreet";
I see the entry changed in the collection.
The configuration mapping is:
Mapper.CreateMap<CustomerAddressForView, CustomerAddress>()
.ForMember(x => x.Id, opt => opt.Ignore());
Any idea?
Update 1
public class Customer
{
public virtual int Id { get; set; }
public virtual string LastName { get; set; }
public virtual Iesi.Collections.Generic.ISet<CustomerAddress> Address { get; set; }
public Customer()
{
Address = new Iesi.Collections.Generic.HashedSet<CustomerAddress>();
}
}
public class CustomerAddress
{
public virtual int Id { get; set; }
public virtual string Street { get; set; }
public virtual Customer Customer { get; set; }
}
The reason why NHibernate isn’t updating the
CustomerAddressobject referenced bycustomer.Addressesis because theaddressvariable gets overwritten with a new object in the call to theMapper.Mapmethod:AutoMapper creates a new
CustomerAddressobject, which isn’t associated to the retrievedCustomer, hence nothing gets updated when you callsession.Save().You need to pass a reference to the retrieved
CustomerAddressobject to AutoMapper in order to update its properties: