zoukankan      html  css  js  c++  java
  • EF扩展 更新指定字段

    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;
            }
        }
  • 相关阅读:
    扩展Dijkstra
    CodeForces 1396E. Distance Matching
    大联盟2
    整式乘除法
    美国数学会众多教授推荐的本科&研究生代数几何经典书籍教材清单
    算法题——立方体的体对角线穿过多少个正方体?
    导数练习题
    导数压轴题
    集合
    著名数学家Ky Fan的故事
  • 原文地址:https://www.cnblogs.com/tangchun/p/7520052.html
Copyright © 2011-2022 走看看