Example #1
0
 /// <summary>
 /// 更新单条数据
 /// </summary>
 /// <typeparam name="T">表的实体类</typeparam>
 /// <param name="model">模型数据</param>
 public static int Update <T>(T model) where T : class
 {
     try
     {
         int rows = 0;
         using (var db = new DemoEntities())
         {
             if (db.Entry(model).State == EntityState.Detached)
             {
                 db.Set <T>().Attach(model);
                 db.Entry(model).State = EntityState.Modified;
             }
             rows += db.SaveChanges();
         }
         return(rows);
     }
     catch (Exception ex)
     {
         WriteException(ex);
         return(0);
     }
 }
Example #2
0
 /// <summary>
 /// 删除单条数据
 /// </summary>
 /// <typeparam name="T">表的实体类</typeparam>
 /// <param name="model">模型数据</param>
 /// <returns>删除行数</returns>
 public static int Delete <T>(T model) where T : class
 {
     try
     {
         int rows = 0;
         using (var db = new DemoEntities())
         {
             db.Entry(model).State = EntityState.Deleted;
             rows += db.SaveChanges();
         }
         return(rows);
     }
     catch (Exception ex)
     {
         WriteException(ex);
         return(0);
     }
 }
Example #3
0
 /// <summary>
 /// 使用查询条件更新数据
 /// </summary>
 /// <typeparam name="T">表的实体类</typeparam>
 /// <param name="action">更新数据动作</param>
 /// <param name="where">表达式</param>
 public static int Update <T>(Action <T> action, Expression <Func <T, bool> > where) where T : class
 {
     try
     {
         int rows = 0;
         using (var db = new DemoEntities())
         {
             var list = db.Set <T>().Where(where);
             foreach (var model in list)
             {
                 action.Invoke(model);
                 db.Entry(model).State = EntityState.Modified;
             }
             rows += db.SaveChanges();
         }
         return(0);
     }
     catch (Exception ex)
     {
         WriteException(ex);
         return(0);
     }
 }