zoukankan      html  css  js  c++  java
  • 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; }
    
        }

    
    
    


  • 相关阅读:
    mysql启动报错:Another MySQL daemon already running with the same unix socket.
    DRBD编译安装中出现的问题及解决小结
    DRBD+Heartbeat+Mysql高可用环境部署
    LVS三种包转发模型调度算法
    nagios环境部署(rhel6.5)
    reorder-list
    二叉树的前序遍历(不用递归)
    最大正方形
    名字的漂亮度
    计算字符个数
  • 原文地址:https://www.cnblogs.com/huangshuqiang/p/6580931.html
Copyright © 2011-2022 走看看