using System.Data.Entity.Infrastructure; using System.Threading.Tasks; /// <summary> /// EF扩展 /// </summary> public static class EFExtensions { /// <summary> /// 更新实体根据字段 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="db">数据库上下文</param> /// <param name="entity">实体</param> /// <param name="fields">更新的字段列表</param> public static int UpdateEntityFields<T>(this ApplicationDbContext db, T entity, IList<string> fields) where T : class { if (entity == null || fields == null || fields.Count == 0) { return 0; } db.Set<T>().Attach(entity); var SetEntry = ((IObjectContextAdapter)db).ObjectContext. ObjectStateManager.GetObjectStateEntry(entity); foreach (var item in fields) { SetEntry.SetModifiedProperty(item); } return db.SaveChanges(); } /// <summary> /// 异步更新实体根据字段 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="db">数据库上下文</param> /// <param name="entity">实体</param> /// <param name="fields">更新字段列表</param> /// <returns>受影响的行数</returns> public static async Task<int> UpdateEntityFieldsAsync<T>(this ApplicationDbContext db, T entity, IList<string> fields) where T : class { if (entity == null || fields == null || fields.Count == 0) { return 0; } db.Set<T>().Attach(entity); var SetEntry = ((IObjectContextAdapter)db).ObjectContext. ObjectStateManager.GetObjectStateEntry(entity); foreach (var item in fields) { SetEntry.SetModifiedProperty(item); } int result = await db.SaveChangesAsync(); return result; } }