我使用数据传输对象在实体框架和业务层和用户层之间传输数据.我有一些疑问,如果我检索一个转换为DTO的对象,我如何在实体框架中更新正确的对象而不只是插入一个副本?
以下代码将从强类型视图更新已在MVC中创建为控制器参数的EF 4实体:
似乎诀窍是在将实体添加到上下文后使用ObjectStateManager将状态从Added更改为Modified.
MyEntities db = new MyEntities(); db.Product.AddObject(product); db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Modified); return db.SaveChanges() > 0;
根据@Sean Mills评论,如果您使用的是EF5:
((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
一个老问题,但万一有人需要代码解决方案:
http://www.mikesdotnetting.com/Article/110/ASP.NET-MVC-Entity-Framework-Modifying-One-to-Many-and-Many-to-Many-Relationships
例:
public void EditArticle( Article article, string articleTypeId, string[] categoryId) { var id = 0; Article art = de.ArticleSet .Include("ArticleTypes") .Include("Categories") .Where(a => a.ArticleID == article.ArticleID) .First(); var count = art.Categories.Count; for (var i = 0; i < count; i++) { art.Categories.Remove(art.Categories.ElementAt(i)); count--; } foreach (var c in categoryId) { id = int.Parse(c); Category category = de.CategorySet .Where(ct => ct.CategoryID == id).First(); art.Categories.Add(category); } art.Headline = article.Headline; art.Abstract = article.Abstract; art.Maintext = article.Maintext; art.DateAmended = DateTime.Now; art.ArticleTypesReference.EntityKey = new EntityKey( "DotnettingEntities.ArticleTypeSet", "ArticleTypeID", int.Parse(articleTypeId) ); de.SaveChanges(); }