当我执行下面的代码时,在Mapper.Map
行的地址中,我可以使用来自模型的正确值,但customer.Address
,ISet
集合未更新session.Save(customer)
行。应该更新,因为address
是参考。
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();
}
如果我这样做:
var address = customer.Address.Where(x => x.Id == myAddressId).First<CustomerAddress>();
address.Street = "MyStreet";
我看到该系列中的条目已更改。
配置映射是:
Mapper.CreateMap<CustomerAddressForView, CustomerAddress>()
.ForMember(x => x.Id, opt => opt.Ignore());
有什么想法吗?
更新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; }
}
答案 0 :(得分:4)
NHibernate没有更新CustomerAddress
引用的customer.Addresses
对象的原因是因为调用中address
变量被新对象覆盖到Mapper.Map
方法:
address = Mapper.Map<CustomerAddressForView, CustomerAddress>(model);
AutoMapper会创建一个新 CustomerAddress
对象,该对象与检索到的Customer
无关,因此在您调用session.Save()
时不会更新任何内容。
您需要将引用传递给检索到的CustomerAddress
对象到AutoMapper才能更新其属性:
var address = customer.Address
.Where(x => x.Id == myAddressId)
.First<CustomerAddress>();
Mapper.Map(model, address); // Updates the existing address