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数据库的创建&删除&选择
    JS实现异步的几种方式
    十种排序算法实例说明总结
    常用的bug管理工具
    Bootstrap+Hbuilder
    从菜鸟的视角看测试!
    安装numpy和matplotlib
    Eclipse在线安装svn
    重新打个招呼
    <USACO09JAN>气象测量/气象牛The Baric Bovineの思路
  • 原文地址:https://www.cnblogs.com/huangshuqiang/p/6580931.html
Copyright © 2011-2022 走看看