EF6+ MVC Insert or update pattern

本文深入探讨了在数据库操作中使用InsertOrUpdate模式进行实体新增与更新的方法,通过检查主键值来决定操作类型。同时介绍了如何在已跟踪实体的状态发生变化时,通过设置Entity状态来实现对数据库的高效操作。文章还提供了实例代码,详细解释了如何在不同的场景下灵活运用这些概念,旨在提高开发者在处理数据库交互时的效率与准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//Insert or update pattern
//A common pattern for some applications is to either Add an entity as new (resulting in a database insert) or Attach an entity as existing and mark it as //modified (resulting in a database update) depending on the value of the primary key. For example, when using database generated integer primary //keys it is common to treat an entity with a zero key as new and an entity with a non-zero key as existing. This pattern can be achieved by setting the //entity state based on a check of the primary key value. For example:
public void InsertOrUpdate(Blog blog) 
{ 
    using (var context = new BloggingContext()) 
    { 
        context.Entry(blog).State = blog.BlogId == 0 ? 
                                   EntityState.Added : 
                                   EntityState.Modified; 
 
        context.SaveChanges(); 
    } 
}

Changing the state of a tracked entity

//You can change the state of an entity that is already being tracked by setting the State property on its entry. For example:
var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" }; 
 
using (var context = new BloggingContext()) 
{ 
    context.Blogs.Attach(existingBlog); 
    context.Entry(existingBlog).State = EntityState.Unchanged; 
 
    // Do some more work...  
 
    context.SaveChanges(); 
}

// Attaching an existing but modified entity to the context

If you have an entity that you know already exists in the database but to which changes may have been made then you can tell the context to attach the entity and set its state to Modified. For example:

var existingBlog = new Blog { BlogId = 1, Name = "ADO.NET Blog" }; 
 
using (var context = new BloggingContext()) 
{ 
    context.Entry(existingBlog).State = EntityState.Modified; 
 
    // Do some more work...  
 
    context.SaveChanges(); 
}

Update Detached entity in EF 6

Blog detachedBlog = new Blog() { Id = 1, Name = "New Blog Again" };

using (var ctx = new BlogDBEntities())
{
  ctx.Entry(detachedBlog).State = EntityState.Modified;  
  ctx.SaveChanges();
}



https://msdn.microsoft.com/en-us/data/jj592676.aspx
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值