asp.net-mvc-3 - 使用Automapper/EF代码优先进行数据库更新

标签 asp.net-mvc-3 ef-code-first automapper

我在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/

相关文章:

entity-framework - 尝试删除非级联实体时 EF 中的异常处理

c# - 名称不匹配时的 Entity Framework 外键

c# - Auto Mapper v4.2.1 - 缺少类型映射配置或不支持的映射

c# - AutoMapper - 扁平化具有很长属性名称的类型

c# - HttpContext.Current.Cache 和 HttpContext.Response.Cache 有什么区别?

c# - Ajax.BeginForm(), OnSuccess - 获取事件目标

asp.net-mvc-3 - 在非MVC项目中使用MvcMailer

c# - 当单个部分需要多个对象时,如何从 View 中动态地将项目添加到我的集合中?

.net - EntityFramework.dll 与 System.Data.Entity.dll -- 歧义

asp.net-mvc - 如何将 EditModel 映射到命令消息?