public int UpData(T model, params string[] proNames)
{ //4.1将 对象 添加到 EF中
DbEntityEntry entry = null; var set = db.Set<T>().Find(DbContextExtensions.GetEntityKey(db, model)); if (set != null)
{ db.Entry<T>(set).State = EntityState.Detached; } entry = db.Entry<T>(model); //4.2先设置 对象的包装 状态为 Unchanged entry.State = EntityState.Unchanged;
//4.3循环 被修改的属性名 数组
foreach (string proName in proNames)
{
//4.4将每个 被修改的属性的状态 设置为已修改状态;后面生成update语句时,就只为已修改的属性 更新
entry.Property(proName).IsModified = true;
} return db.SaveChanges(); }
public static class DbContextExtensions
{
public static int GetEntityKey(this DbContext context, object entity)
{
try
{
string name = entity.GetType().ToString().Replace("Model.",""); var adapter = context as IObjectContextAdapter;
EntityKey enkey = adapter.ObjectContext.CreateEntityKey(name, entity); string id = enkey.EntityKeyValues[0].Value.ToString();
return int.Parse(id);
}
catch
{
return 0;
} }
}