EF中更新操作 ID自增但不是主鍵 ;根據ViewModel更新實體的部分屬性


//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() == "&nbsp;")//一些屬性由於前台的原因 傳過來的值會是&nbsp; 這里做一下處理 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;
        }
PS:eg一個ViewModel:
 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; }

    }

 


 
         

 



 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM