直接使用提交过来的类来更新字段EntityState.Modified并过滤null值的方法

时间:2023-03-09 07:05:56
直接使用提交过来的类来更新字段EntityState.Modified并过滤null值的方法
public static void UpdateModel<T>(T entity, DbContext db) where T : class
{
db.Set<T>().Attach(entity);
foreach (System.Reflection.PropertyInfo p in entity.GetType().GetProperties())
{
if (p.GetValue(entity) != null)
{
db.Entry(entity).Property(p.Name).IsModified = true;
}
}
db.SaveChanges();
}