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;
            }
        }
  • 相关阅读:
    bzoj1007: [HNOI2008]水平可见直线(单调栈)
    1264: [AHOI2006]基因匹配Match(动态规划神题)
    bzoj1433: [ZJOI2009]假期的宿舍(最大二分图匹配)
    bzoj3931: [CQOI2015]网络吞吐量(spfa+网络流)
    [ZJOI2007]矩阵游戏
    [HAOI2007]覆盖问题
    [ZJOI2008]树的统计
    [ZJOI2010]数字计数
    [HAOI2006]旅行
    [HAOI2006]数字序列
  • 原文地址:https://www.cnblogs.com/tangchun/p/7520052.html
Copyright © 2011-2022 走看看