1.更新指定字段
Customer cus = new Customer(){id="20123223311112221",name="王同学",comp="义乌动力机械有限公司",intro="优秀"};
cus.updateTime = DateTime.Now;
db.Entry(cus).State = EntityState.Unchanged;
db.Entry(cus).Property("name").IsModified = true;
db.Entry(cus).Property("intro").IsModified = true;
db.Entry(cus).Property("updateTime").IsModified = true;
2.更新整个实体
错误的方法:
Customer cus = new Customer(){id="20123223311112221",name="王同学",comp="义乌动力机械有限公司",intro="优秀"};
cus.updateTime = DateTime.Now;
db.Entry(cus).State = EntityState.Modified;
正确的方法:
/// <summary>
/// 更新数据实体
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="context"></param>
/// <param name="entity"></param>
/// <param name="exists"></param>
public static void UpdateEntity<T>(this DbContext context,T entity,Func<T,bool> exists) where T:class
{
T model = context.Set<T>().Where(exists).FirstOrDefault();
if(model == null)
{
context.Entry(entity).State = EntityState.Modified;
}
else
{
context.Entry(model).CurrentValues.SetValues(entity);
}
}