更新实体框架对象

use*_*278 24 entity entity-framework

我使用数据传输对象在实体框架和业务层和用户层之间传输数据.我有一些疑问,如果我检索一个转换为DTO的对象,我如何在实体框架中更新正确的对象而不只是插入一个副本?

Rob*_*Rob 28

以下代码将从强类型视图更新已在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;
Run Code Online (Sandbox Code Playgroud)

根据@Sean Mills评论,如果您使用的是EF5:

 ((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);
Run Code Online (Sandbox Code Playgroud)

  • 如果ObjectStateManager不是您的上下文的属性,请尝试((System.Data.Entity.Infrastructure.IObjectContextAdapter)db).ObjectContext http://stackoverflow.com/a/8968643/678338 (2认同)

Bar*_*art 7

一个老问题,但万一有人需要代码解决方案:

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();
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ers 2

您需要在 DTO 中包含主键或备用键,然后在更新时将该键匹配回正确的 EF 实体。