zoukankan      html  css  js  c++  java
  • EF操作扩展之async

    EF的操作类网上很多类,我只是把我在平时项目中的类进行一些改进和扩展,扩展了部分同步和异步的EF操作

    接口

     1 /// <summary>
     2     /// 接口数据操作基础类
     3     /// </summary>
     4     /// <typeparam name="Key"></typeparam>
     5     /// <typeparam name="Entity"></typeparam>
     6     public interface IBaseOpertion<TEntity, TKey> where TEntity : class
     7     {
     8         /// <summary>
     9         ///  添加数据
    10         /// </summary>
    11         /// <param name="tableName"></param>
    12         /// <param name="table"></param>
    13         /// <returns></returns>
    14         int AddTable(string tableName, DataTable table);
    15         Task<int> AddTableAsy(string tableName, DataTable table);
    16         /// <summary>
    17         /// 添加
    18         /// </summary>
    19         /// <param name="entity"></param>
    20         /// <returns></returns>
    21         TEntity AddEntity(TEntity entity);
    22         Task<TEntity> AddEntityAsy(TEntity entity);
    23         /// <summary>
    24         ///  批量添加
    25         /// </summary>
    26         /// <param name="list"></param>
    27         /// <returns></returns>
    28         int AddEntity(List<TEntity> list);
    29         Task<int> AddEntityAys(List<TEntity> list);
    30         /// <summary>
    31         /// 修改
    32         /// </summary>
    33         /// <param name="entity"></param>
    34         /// <returns></returns>
    35         TEntity UpdateEntity(TEntity entity);
    36         Task<TEntity> UpdateEntityAsy(TEntity entity);
    37         /// <summary>
    38         /// 删除 实体
    39         /// </summary>
    40         /// <param name="TEntity"></param>
    41         /// <returns></returns>
    42         int DelEntity(TEntity entity);
    43         Task<int> DelEntityAsy(TEntity entity);
    44         // <summary>
    45         /// 删除  主键
    46         /// </summary>
    47         /// <param name="TEntity"></param>
    48         /// <returns></returns>
    49         int DelEntity(TKey key);
    50         Task<int> DelEntityAsy(TKey key);
    51         // <summary>
    52         /// 删除  条件
    53         /// </summary>
    54         /// <param name="TEntity"></param>
    55         /// <returns></returns>
    56         int DelEntity(Dictionary<string,object> where);
    57         Task<int> DelEntityAsy(Dictionary<string, object> where);
    58 
    59         /// <summary>
    60         /// 根据ID进行查询
    61         /// </summary>
    62         /// <param name="key"></param>
    63         /// <returns></returns>
    64         TEntity GetEntityByID(TKey key);
    65         Task<TEntity> GetEntityByIDAsy(TKey key);
    66         /// <summary>
    67         /// 根据sql进行查询
    68         /// </summary>
    69         /// <param name="predicate"></param>
    70         /// <returns></returns>
    71         List<TEntity> GetEntityQuerySql(string sql);
    72         Task<List<TEntity>> GetEntityQuerySqlAsy(string sql);
    73         /// <summary>
    74         /// 根据条件进行查询
    75         /// </summary>
    76         /// <param name="fun"></param>
    77         /// <returns></returns>
    78         List<TEntity> GetEntityLisrByWhere(Expression<Func<TEntity, bool>> fun);
    79         Task<List<TEntity>> GetEntityLisrByWhereAsy(Expression<Func<TEntity, bool>> fun);
    80 
    81         /// <summary>
    82         /// 根据条件进行查询
    83         /// </summary>
    84         /// <param name="fun"></param>
    85         /// <returns></returns>
    86         TEntity GetEntityByWhere(Expression<Func<TEntity, bool>> fun);
    87         Task<TEntity> GetEntityByWhereAsy(Expression<Func<TEntity, bool>> fun);
    88     }
    View Code

    实现类

      1 /// <summary>
      2     /// 数据实体操作
      3     /// </summary>
      4     /// <typeparam name="TEntity"></typeparam>
      5     /// <typeparam name="TKey"></typeparam>
      6     public abstract class BaseService<TEntity, TKey> : IBaseOpertion<TEntity, TKey> where TEntity : class
      7     {
      8         public virtual TEntity AddEntity(TEntity entity)
      9         {
     10             using (DBContextHelper dbHelper = new DBContextHelper())
     11             {
     12                 TEntity newEntity = dbHelper.Set<TEntity>().Add(entity);
     13                 if (dbHelper.SaveChanges() > 0)
     14                     return newEntity;
     15                 return null;
     16             }
     17         }
     18         public virtual async Task<TEntity> AddEntityAsy(TEntity entity) {
     19             using (DBContextHelper dbHelper = new DBContextHelper())
     20             {
     21                 TEntity newEntity = dbHelper.Set<TEntity>().Add(entity);
     22                 int temp =await dbHelper.SaveChangesAsync();
     23                 if (temp > 0)
     24                     return newEntity;
     25                 return null;
     26             }
     27         }
     28 
     29         public virtual TEntity UpdateEntity(TEntity entity)
     30         {
     31             using (DBContextHelper dbHelper = new DBContextHelper())
     32             {
     33                 DbSet<TEntity> dbSet = dbHelper.Set<TEntity>();
     34                 DbEntityEntry<TEntity> entry = dbHelper.Entry<TEntity>(entity);
     35                 if (entry.State == System.Data.Entity.EntityState.Detached)
     36                 {
     37                     dbSet.Attach(entity);
     38                     entry.State = System.Data.Entity.EntityState.Modified;
     39                 }
     40                 if (dbHelper.SaveChanges() >= 0)
     41                     return entity;
     42                 return null;
     43             }
     44         }
     45         public virtual async Task<TEntity> UpdateEntityAsy(TEntity entity)
     46         {
     47             using (DBContextHelper dbHelper = new DBContextHelper())
     48             {
     49                 DbSet<TEntity> dbSet = dbHelper.Set<TEntity>();
     50                 DbEntityEntry<TEntity> entry = dbHelper.Entry<TEntity>(entity);
     51                 if (entry.State == System.Data.Entity.EntityState.Detached)
     52                 {
     53                     dbSet.Attach(entity);
     54                     entry.State = System.Data.Entity.EntityState.Modified;
     55                 }
     56                 int result = await dbHelper.SaveChangesAsync();
     57                 if (result >= 0)
     58                     return entity;
     59                 return null;
     60             }
     61         }
     62 
     63         public virtual int DelEntity(TEntity entity)
     64         {
     65             using (DBContextHelper dbHelper = new DBContextHelper())
     66             {
     67                 dbHelper.Set<TEntity>().Remove(entity);
     68                 return dbHelper.SaveChanges();
     69             }
     70         }
     71         public virtual async Task<int> DelEntityAsy(TEntity entity)
     72         {
     73             using (DBContextHelper dbHelper = new DBContextHelper())
     74             {
     75                 dbHelper.Set<TEntity>().Remove(entity);
     76                 return await dbHelper.SaveChangesAsync();
     77             }
     78         }
     79 
     80 
     81         public virtual TEntity GetEntityByID(TKey key)
     82         {
     83             using (DBContextHelper dbHelper = new DBContextHelper())
     84             {
     85                 var entity = dbHelper.Set<TEntity>().Find(key);
     86                 return entity;
     87             }
     88         }
     89         public virtual async Task<TEntity> GetEntityByIDAsy(TKey key)
     90         {
     91             using (DBContextHelper dbHelper = new DBContextHelper())
     92             {
     93                 return await dbHelper.Set<TEntity>().FindAsync(key);
     94             }
     95         }
     96 
     97 
     98 
     99 
    100         public virtual List<TEntity> GetEntityQuerySql(string sql)
    101         {
    102             using (DBContextHelper dbHelper = new DBContextHelper())
    103             {
    104                 var entity = dbHelper.Set<TEntity>().SqlQuery(sql, new object[] { }).ToList();
    105                 return entity;
    106             }
    107         }
    108         public virtual async Task<List<TEntity>> GetEntityQuerySqlAsy(string sql)
    109         {
    110             using (DBContextHelper dbHelper = new DBContextHelper())
    111             {
    112                 return await dbHelper.Set<TEntity>().SqlQuery(sql, new object[] { }).ToListAsync();
    113             }
    114         }
    115 
    116 
    117 
    118 
    119         public virtual List<TEntity> GetEntityLisrByWhere(Expression<Func<TEntity, bool>> fun)
    120         {
    121             using (DBContextHelper dbHelper = new DBContextHelper())
    122             {
    123                 var entity = dbHelper.Set<TEntity>().AsNoTracking().Where(fun).ToList();
    124                 return entity;
    125             }
    126         }
    127         public virtual async Task<List<TEntity>> GetEntityLisrByWhereAsy(Expression<Func<TEntity, bool>> fun)
    128         {
    129             using (DBContextHelper dbHelper = new DBContextHelper())
    130             {
    131                return await dbHelper.Set<TEntity>().AsNoTracking().Where(fun).ToListAsync();
    132             }
    133         }
    134 
    135         public virtual int AddEntity(List<TEntity> list)
    136         {
    137             using (DBContextHelper dbHelper = new DBContextHelper())
    138             {
    139                 dbHelper.Configuration.AutoDetectChangesEnabled = false;
    140                 try
    141                 {
    142                     dbHelper.Set<TEntity>().AddRange(list);
    143                     return dbHelper.SaveChanges();
    144                 }
    145                 finally
    146                 {
    147                     dbHelper.Configuration.AutoDetectChangesEnabled = true;
    148                 }
    149             }
    150         }
    151         public virtual async Task<int> AddEntityAys(List<TEntity> list)
    152         {
    153             using (DBContextHelper dbHelper = new DBContextHelper())
    154             {
    155                 dbHelper.Configuration.AutoDetectChangesEnabled = false;
    156                 try
    157                 {
    158                     dbHelper.Set<TEntity>().AddRange(list);
    159                     return await dbHelper.SaveChangesAsync();
    160                 }
    161                 finally
    162                 {
    163                     dbHelper.Configuration.AutoDetectChangesEnabled = true;
    164                 }
    165             }
    166         }
    167 
    168         public virtual int DelEntity(TKey key)
    169         {
    170             using (DBContextHelper dbHelper = new DBContextHelper())
    171             {
    172                 var entity = dbHelper.Set<TEntity>().Find(key);
    173                 dbHelper.Set<TEntity>().Remove(entity);
    174                 return dbHelper.SaveChanges();
    175             }
    176         }
    177         public virtual async Task<int> DelEntityAsy(TKey key)
    178         {
    179             using (DBContextHelper dbHelper = new DBContextHelper())
    180             {
    181                 var entity = dbHelper.Set<TEntity>().Find(key);
    182                 dbHelper.Set<TEntity>().Remove(entity);
    183                 return await dbHelper.SaveChangesAsync(); ;
    184             }
    185         }
    186 
    187         public virtual int DelEntity(Dictionary<string, object> where)
    188         {
    189             using (DBContextHelper dbHelper = new DBContextHelper())
    190             {
    191                 if (where == null || where.Keys.Count <= 0) return 0;
    192                 StringBuilder sb = new StringBuilder();
    193                 List<string> KeyList = new List<string>(where.Keys);
    194                 List<SqlParameter> plist = new List<SqlParameter>();
    195                 for (int i = 0, j = KeyList.Count; i < j; i++)
    196                 {
    197                     plist.Add(new SqlParameter()
    198                     {
    199                         ParameterName = KeyList[i],
    200                         Value = where[KeyList[i]]
    201                     });
    202                     if (i == j - 1)
    203                     {
    204                         sb.Append(string.Format(" {0}=@{0} ", KeyList[i]));
    205                     }
    206                     sb.Append(string.Format("{0}=@{0} and ", KeyList[i]));
    207                 }
    208                 string TableName = this.GetType().Name;
    209                 string sql = string.Format("delete from [{0}] where {1}", TableName, sb.ToString());
    210                 dbHelper.Set<TEntity>().SqlQuery(sql, plist);
    211                 return dbHelper.SaveChanges();
    212             }
    213         }
    214         public virtual async Task<int> DelEntityAsy(Dictionary<string, object> where)
    215         {
    216             using (DBContextHelper dbHelper = new DBContextHelper())
    217             {
    218                 if (where == null || where.Keys.Count <= 0) return 0;
    219                 StringBuilder sb = new StringBuilder();
    220                 List<string> KeyList = new List<string>(where.Keys);
    221                 List<SqlParameter> plist = new List<SqlParameter>();
    222                 for (int i = 0, j = KeyList.Count; i < j; i++)
    223                 {
    224                     plist.Add(new SqlParameter()
    225                     {
    226                         ParameterName = KeyList[i],
    227                         Value = where[KeyList[i]]
    228                     });
    229                     if (i == j - 1)
    230                     {
    231                         sb.Append(string.Format(" {0}=@{0} ", KeyList[i]));
    232                     }
    233                     sb.Append(string.Format("{0}=@{0} and ", KeyList[i]));
    234                 }
    235                 string TableName = this.GetType().Name;
    236                 string sql = string.Format("delete from [{0}] where {1}", TableName, sb.ToString());
    237                 dbHelper.Set<TEntity>().SqlQuery(sql, plist);
    238                 return await dbHelper.SaveChangesAsync();
    239             }
    240         }
    241 
    242         public virtual TEntity GetEntityByWhere(Expression<Func<TEntity, bool>> fun)
    243         {
    244             using (DBContextHelper dbHelper = new DBContextHelper())
    245             {
    246                 var entity = dbHelper.Set<TEntity>().AsNoTracking().Where(fun).FirstOrDefault();
    247                 return entity;
    248             }
    249         }
    250         public virtual async Task<TEntity> GetEntityByWhereAsy(Expression<Func<TEntity, bool>> fun)
    251         {
    252             using (DBContextHelper dbHelper = new DBContextHelper())
    253             {
    254                 return await dbHelper.Set<TEntity>().AsNoTracking().Where(fun).FirstOrDefaultAsync();
    255             }
    256         }
    257 
    258 
    259 
    260         public virtual int AddTable(string tableName, DataTable table)
    261         {
    262             if (string.IsNullOrEmpty(tableName) || table==null || table.Rows.Count<0)
    263                 return -1;
    264             else
    265             {
    266                 using (DBContextHelper dbHelper = new DBContextHelper())
    267                 {
    268                     try
    269                     {
    270                         if (dbHelper.Database.Connection.State != ConnectionState.Open)
    271                         {
    272                             var bulkCopy = new SqlBulkCopy((SqlConnection)dbHelper.Database.Connection);
    273                             bulkCopy.DestinationTableName = tableName;
    274                             bulkCopy.WriteToServer(table);
    275                         }
    276                         return table.Rows.Count;
    277                     }
    278                     catch (Exception e)
    279                     {
    280                         throw e;
    281                     }
    282                     finally {
    283                         if (dbHelper.Database.Connection.State != ConnectionState.Closed)
    284                         {
    285                             dbHelper.Database.Connection.Close();
    286                         }
    287                     }
    288                 }
    289             }
    290         }
    291         public virtual async Task<int> AddTableAsy(string tableName, DataTable table)
    292         {
    293             if (string.IsNullOrEmpty(tableName) || table == null || table.Rows.Count < 0)
    294                 return -1;
    295             else
    296             {
    297                 using (DBContextHelper dbHelper = new DBContextHelper())
    298                 {
    299                     try
    300                     {
    301                         if (dbHelper.Database.Connection.State != ConnectionState.Open)
    302                         {
    303                             var bulkCopy = new SqlBulkCopy((SqlConnection)dbHelper.Database.Connection);
    304                             bulkCopy.DestinationTableName = tableName;
    305                             await bulkCopy.WriteToServerAsync(table);
    306                         }
    307                         return table.Rows.Count;
    308                     }
    309                     catch (Exception e)
    310                     {
    311                         throw e;
    312                     }
    313                     finally
    314                     {
    315                         if (dbHelper.Database.Connection.State != ConnectionState.Closed)
    316                         {
    317                             dbHelper.Database.Connection.Close();
    318                         }
    319                     }
    320                 }
    321             }
    322         }
    323     }
    View Code
  • 相关阅读:
    20155334 2016-2017-2 《Java程序设计》第四周学习总结
    20155334 2016-2017-2 《Java程序设计》第三周学习总结
    20155334 2016-2017-2 《Java程序设计》第二周学习总结
    20155334 2016-2017-2 《Java程序设计》第一周学习总结
    虚拟机与Linux的初体验
    20155334的第二次随笔
    使用Maven工程
    观察者模式(observer)
    GreenPlum之进程会话管理篇
    Linux下crontab命令添加Kettle作业定时任务
  • 原文地址:https://www.cnblogs.com/kq123321/p/6406452.html
Copyright © 2011-2022 走看看