DataContext.ApplyCurrentValues() 需要 entitySetName,它是什么?
我认为代码会相同:
public void Edit(Products p)
{
DataContext.ApplyCurrentValues("Products", p);
DataContext.SaveChanges();
}
是否正确?
最佳答案
这是 .Net 4.0
对于这个例子,假设我们正在处理 Product 对象。
using (DBEntities context = new DBEntities())
{
//Must attach first and change the state to modified
context.Products.Attach(product);
//If you are using .Net 4.1 then you can use this line instead:
//context.Entry(
context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified);
context.SaveChanges();
}
如果您使用的是 .Net 4.1,则可以使用“context.Entry(...)”代替“context.ObjectStateManager.ChangeObjectState(product, EntityState.Modified)”,如下所示: Example of context.Entry()
这是最直接的方法。它不需要您先从数据库中提取对象,您只需提供您正在修改的对象即可。唯一的缺点是这会更新所有字段,而不仅仅是单个字段。
关于c# - 如何在 Entity Framework 中编辑对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5014347/