DBContext.MyModel.Update(myobject)在哪里? [英] Where is DBContext.MyModel.Update(myobject) ?

查看:80
本文介绍了DBContext.MyModel.Update(myobject)在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新数据库中现有实体的最佳方法是什么?

我从我的mvc控制器收到了一个模型,我想用它来更新数据库。

What is the best way to update an existing entity in the db?
I have received a model from my mvc controller and I want to update the database with it.

[HttpPost]

public ActionResult Edit(产品)

{

  MyDBContext db = new MyDBContext ;

  db.Products.Update(product);

}

[HttpPost]
public ActionResult Edit(Product product)
{
 MyDBContext db = new MyDBContext;
 db.Products.Update(product);
}

我从视图中获得的产品有ID,为什么我不能只更新它?

The product that I am getting from the view has the ID, so why can't I just update it?

当然我没有"找到"上下文中的对象再次更新每个属性,如下所示:

Surely I don't have to "find" the object in the context again and then update each one of the properties like this:

[HttpPost]

public ActionResult Edit(Product product)

{

  MyDBContext db = new MyDBContext;

  Product pr = db.Products.Find(product.ID);

  pr.fname = product.fname;

  pr.lname = product.lname;

  pr.age = product.age;

  ... 25其他房产

 

  db.SaveChanges();

}

[HttpPost]
public ActionResult Edit(Product product)
{
 MyDBContext db = new MyDBContext;
 Product pr = db.Products.Find(product.ID);
 pr.fname = product.fname;
 pr.lname = product.lname;
 pr.age = product.age;
 ...25 other properties
 
 db.SaveChanges();
}

推荐答案

嗨Terrence,

Hi Terrence,

这在CTP4中是可能的(但不是非常优雅或可发现),但它在CTP5中会更清洁。下面是一些将Update方法添加到派生上下文的代码:

This is possible (but not very elegant or discoverable) in CTP4, it will however be much cleaner in CTP5. Here is some code to add an Update method to your derived context:


public class ProductContext : DbContext
{
  public DbSet<Product> Products { get; set; }

  ...

  public void Update<T>(T entity)
    where T : class
  {
    this.Set<T>().Attach(entity);
    base.ObjectContext.ObjectStateManager.ChangeObjectState(entity, System.Data.EntityState.Modified);
  }
}


这篇关于DBContext.MyModel.Update(myobject)在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆