Kin*_*tes 54 c# entity-framework entity-framework-6
我已经阅读了很多关于在Entity Framework中保存分离实体的帖子.所有这些似乎都适用于旧版本的Entity Framework.它们引用了似乎不存在的ApplyCurrentValues和ChangeObjectState等方法.一时兴起,我决定尝试通过intellisense找到的方法,我想确保这是正确的方法,因为我无法看到幕后发生的事情:
public void SaveOrder(Order order)
{
using (VirtualWebEntities db = new VirtualWebEntities())
{
db.Orders.Attach(order);
db.Entry(order).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
这是更新已更改的现有项目的正确方法吗?
Ste*_*ngs 89
是的,这是正确的.本文介绍了添加和附加实体的各种方法,它提供了以下示例:
var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" };
using (var context = new BloggingContext())
{
// The next step implicitly attaches the entity
context.Entry(existingBlog).State = EntityState.Modified;
// Do some more work...
context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)
由于EF不知道哪些属性与数据库中的属性不同,因此它将全部更新:
当您将状态更改为Modified时,实体的所有属性都将标记为已修改,并且在调用SaveChanges时,所有属性值都将发送到数据库.
为避免这种情况,您可以手动设置修改哪些属性,而不是设置整个实体状态:
using (var context = new BloggingContext())
{
var blog = context.Blogs.Find(1);
context.Entry(blog).Property(u => u.Name).IsModified = true;
// Use a string for the property name
context.Entry(blog).Property("Name").IsModified = true;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46151 次 |
| 最近记录: |