[英]Saving AutoMapper mapped Collections of Entities using Entity Framework
[英]Context is not updating loaded entity after being mapped using AutoMapper
在我的代码中,我使用其id
加载 entity
,然后使用AutoMapper
更新其内容,最后调用Context.SaveChanges
。 但它不起作用! 。 但是当我手动 设置属性时它会生效 ! 怎么了 ?
var entity = Context.MyEntities.Find(id);
entity = Mapper.Map<MyEntity>(viewModel);
Context.SaveChanges;
但是这个有效:
var entity = Context.MyEntities.Find(id);
entity.SomeProp = viewModel.SomeProp;
Context.SaveChanges;
然后使用AutoMapper更新其内容
事实并非如此 - Mapper.Map<MyEntity>(viewModel)
返回MyEntity
类的新实例。 它不会更新现有实例的属性。 您应该将新实例附加到上下文:
var entity = Context.MyEntities.Find(id); // this line is useless
entity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(entity);
Context.SaveChanges;
在创建新实体时,从上下文中检索实体也没有意义。 您正在重用相同的变量来保存对不同对象的引用,这是令人困惑的。 真正发生的事情可以用这种方式描述:
var entityFromDb = Context.MyEntities.Find(id);
var competelyNewEntity = Mapper.Map<MyEntity>(viewModel);
Context.MyEntities.Attach(competelyNewEntity);
Context.SaveChanges;
在第二个选项中,您正在更新实体的属性,该属性存在于上下文中,您无需附加它。
BTW有第三个选项(并且最好) - 使用另一种映射方法,它更新目标实体:
var entity = Context.MyEntities.Find(id);
Mapper.Map(viewModel, entity); // use this method for mapping
Context.SaveChanges;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.