更新实体框架对象

时间:2009-03-08 14:32:00

标签: entity-framework entity

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

5 个答案:

答案 0 :(得分: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;

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

 ((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Added);

答案 1 :(得分: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();
}

答案 2 :(得分:4)

//I am replacing player :)
public ActionResult ProductEdit(string Id, Product product)
{
    int IdInt = DecyrptParameter(Id);
    MyEntities db = new MyEntities();

    var productToDetach = db.Products.FirstOrDefault(p=> p.Id == IdInt);
    if (product == null)
        throw new Exception("Product already deleted"); //I check if exists, maybe additional check if authorised to edit
    db.Detach(productToDetach);

    db.AttachTo("Products", product);
    db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Modified);

    db.SaveChanges();
    ViewData["Result"] = 1; // successful result
    return View();
}

答案 3 :(得分:2)

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

答案 4 :(得分:2)

这适用于EF 5:https://stackoverflow.com/a/11749716/540802

db.Entry(product).State = EntityState.Modified;