我在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();
由于仅显示有限的字段来更新现有客户,因此我使用了不同的 View 模型和客户转换器来处理现有客户。
问题是,使用上述代码,客户记录未更新。
我发现,如果删除自定义转换,则会更新客户记录。
即
Mapper.CreateMap<ExistingCustomerViewModel, Customer>().ForMember(dest => dest.CustomerId, opt => opt.Ignore());
可以正常工作,但是我失去了应用自定义映射的能力。
我想念什么吗?感谢您的帮助!
谢谢!巴拉
最佳答案
我终于决定改变我的方法。阅读了以下文章
http://lostechies.com/jimmybogard/2009/09/18/the-case-for-two-way-mapping-in-automapper/
我决定仅将Automapper用于实体到 View 模型的映射。在HttpPost事件期间,我正在手动将 View 模型的属性分配给实体。当然,它使我的代码变得繁琐,但确实可以控制进入数据库的内容。
干杯!
巴拉
关于asp.net-mvc-3 - 使用Automapper/EF代码优先进行数据库更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8210738/