//ID自增但不是主鍵的情況
public int Update_join<TEntity>(TEntity entity) where TEntity : class { dbcontext.Set<TEntity>().Attach(entity); PropertyInfo[] props = entity.GetType().GetProperties(); foreach (PropertyInfo prop in props) { if(prop.Name=="ID")continue; if (prop.GetValue(entity, null) != null) { if (prop.GetValue(entity, null).ToString() == " ")//一些屬性由於前台的原因 傳過來的值會是 這里做一下處理 dbcontext.Entry(entity).Property(prop.Name).CurrentValue = null; dbcontext.Entry(entity).Property(prop.Name).IsModified = true; } } return dbcontext.SaveChanges(); }
調用方式:db.Update_join(partySummaryTableEntity);
//根據ViewModel更新實體的部分屬性
public int UpdateEntityFields<TEntity>(TEntity entity, List<string> fileds) where TEntity : class { if (entity != null && fileds != null) { dbcontext.Set<TEntity>().Attach(entity); var SetEntry = ((IObjectContextAdapter)dbcontext).ObjectContext. ObjectStateManager.GetObjectStateEntry(entity); foreach (var t in fileds) { SetEntry.SetModifiedProperty(t); } } return dbcontext.SaveChanges();
}
//上面的參數list是將ViewModel的屬性整理成的集合,方法如下
public static List<string> GetDeleteFiles() { List<string> list = new List<string>(); PropertyInfo[] props = new DeleteEntity().GetType().GetProperties();//得到ViewModel屬性集合 foreach (PropertyInfo propertyInfo in props) { list.Add(propertyInfo.Name); } return list; }
public class DeleteEntity : INDeleteAudited { public bool F_DeleteMark { get; set; } /// <summary> /// 刪除實體的用戶 /// </summary> public string F_DeleteUserId { get; set; } /// <summary> /// 刪除實體時間 /// </summary> public DateTime? F_DeleteTime { get; set; } }