Update entity framework objects

前端 未结 5 1111
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 14:59

I transfer data between the entity framework and the business layer and user layer by using Data Transfer Objects. I do have some doubt, if I retrieve an object which is con

5条回答
  •  猫巷女王i
    2020-12-08 15:29

    The following code will update an EF 4 entity that has been created as a controller parameter in MVC from a strongly typed view:

    It seems the trick is to use the ObjectStateManager to change the state from Added to Modified once the entity has been added to the context.

    MyEntities db = new MyEntities();
    db.Product.AddObject(product);
    db.ObjectStateManager.ChangeObjectState(product, System.Data.EntityState.Modified);
    return db.SaveChanges() > 0;
    

    As per @Sean Mills comment if you are using EF5 use:

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

提交回复
热议问题