使用AutoMapper更新条目,条目由LINQ获取

时间:2012-02-14 14:25:45

标签: c# nhibernate automapper

当我执行下面的代码时,在Mapper.Map行的地址中,我可以使用来自模型的正确值,但customer.AddressISet集合未更新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; }
}

1 个答案:

答案 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