我在MVC / EF Code First项目中使用Automapper。在将ViewModel映射到View时,我使用的是继承自TypeConverter的客户转换器类。我正在使用以下代码设置映射:
Mapper.CreateMap<CustomerViewModel, Customer>().ConvertUsing<CustomerConverter>();
其中CustomerConverter是我的TypeConverter类。
这在创建新的Customer实体并保存到db
时工作正常Customer customer = Mapper.Map<CustomerViewModel, Customer>(viewModel);
dbEntities.Customer.Add(customer);
dbEntities.SaveChanges();
但在编辑现有客户时,我发现客户对象的更改未得到保存。
我用来处理现有客户更新的代码如下
var customer = dbEntities.Customer.Single(a => a.CustomerId == viewModel.CustomerId.Value);
Mapper.CreateMap<ExistingCustomerViewModel, Customer>().ForMember(dest => dest.CustomerId, opt => opt.Ignore()).ConvertUsing<ExistingCustomerConverter>();
Mapper.Map<ExistingCustomerViewModel, Customer>(viewModel, customer);
dbEntities.Entry(customer).State = EntityState.Modified;
dbEntities.SaveChanges();
我使用不同的viewmodel和customer转换器来处理现有客户,因为我只显示有限的字段来更新现有客户。
问题是,使用上面的代码,客户记录不会更新。 我发现,如果我删除自定义转换,则会更新客户记录。
即,
Mapper.CreateMap<ExistingCustomerViewModel, Customer>().ForMember(dest => dest.CustomerId, opt => opt.Ignore());
工作正常,但我无法应用自定义映射。
我错过了什么吗?谢谢你的帮助!
谢谢!巴拉
答案 0 :(得分:1)
我终于决定改变我的做法。阅读了下面的文章 http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/ 我决定仅将Automapper用于实体到视图模型的映射。在HttpPost事件期间,我手动将视图模型中的属性分配给实体。当然,它使我的代码充满活力,但它确实让我可以控制进入数据库的内容。 干杯! 巴拉