EF中更新操作 ID自增但不是主键 ;根据ViewModel更新实体的部分属性

时间:2023-03-08 23:36:53
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; } }