使用Attach和Detach来实现更新的时候避免逐一赋值的麻烦

之前都是用扩展方法来copy属性值,不过兼容性不是很好。(关于这个扩展方法可以参照这个 博客),不过我们可以通过下方的代码来实现,由于是微软提供的功能,所以不需要考虑兼容性问题:
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using (NorthwindEntities ctx = new NorthwindEntities())
{
var query = (from q in ctx.Employees
select q).FirstOrDefault();//首先获取记录
query.FirstName = "FIRST";//更改记录
ctx.Entry(query).State = System.Data.EntityState.Detached;//把当前实体从上下文中detach掉,否则在Update方法中无法更新
int result = Update(query);//调用更新方法
}
}
private int Update(Employee entity)
{
string error = string.Empty;
using (NorthwindEntities ctx = new NorthwindEntities())
{
try
{
ctx.Entry(entity).State = System.Data.EntityState.Modified;//指定状态为更新
return ctx.SaveChanges();//保存
}
catch (DbEntityValidationException ex)
{
foreach (var item in ex.EntityValidationErrors)
{
foreach (var item2 in item.ValidationErrors)
{
error = string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage);
}
}
}

}
return 1;
}
}
关于更多的Entity State请参照:
http://msdn.microsoft.com/en-us/data/jj592676.aspx
————————————————
版权声明:本文为CSDN博主「mx5721」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/mx5721/article/details/25220505

转 https://blog.csdn.net/mx5721/article/details/25220505

posted @   dreamw  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2021-06-22 mysql安装之初始化报错:mysqld: [ERROR] Found option without preceding group in config file G:\mysql\my.ini at
2021-06-22 .NET面试题大全(C#面试题)2020更新
2021-06-22 mysql 高版本 sql_mode=only_full_group_by 问题解决方法
2021-06-22 Mysql8.0出现this is incompatible with sql_mode=only_full_group_by
2021-06-22 mysql8 设置sql_mode后不能启动
2021-06-22 mysql.ini 配置
2021-06-22 解决Mysql安装之后没有my.ini配置文件问题
点击右上角即可分享
微信分享提示