首先简单封装了个DbContext

  1  public class DbContext
  2     {
  3         #region 属性字段
  4         private static string _connectionString;
  5 
  6         /// <summary>
  7         /// 连接字符串 by beck.huang 2018-05-08 09:56:05
  8         /// </summary>
  9         public static string ConnectionString
 10         {
 11             get { return _connectionString; }
 12             set { _connectionString = value; }
 13         }
 14 
 15         private static DbType _dbType;
 16 
 17         /// <summary>
 18         /// 数据库类型 by beck.huang 2018-05-08 09:58:03
 19         /// </summary>
 20         public static DbType DbType
 21         {
 22             get { return _dbType; }
 23             set { _dbType = value; }
 24         }
 25 
 26 
 27         private SqlSugarClient _db;
 28 
 29         /// <summary>
 30         /// 数据连接对象 by beck.huang 2018-05-08 10:00:14
 31         /// </summary>
 32         public SqlSugarClient Db
 33         {
 34             get { return _db; }
 35             private set { _db = value; }
 36         }
 37 
 38         /// <summary>
 39         /// 数据库上下文实例(自动关闭连接) by beck.huang 2018-05-08 09:47:30
 40         /// </summary>
 41         public static DbContext Context
 42         {
 43             get
 44             {
 45                 return new DbContext();
 46             }
 47 
 48         }
 49         #endregion
 50 
 51         #region 构造函数
 52 
 53         /// <summary>
 54         /// 功能描述:构造函数
 55         /// 作  者:beck.huang
 56         /// 创建日期:2018-05-08 09:47:24
 57         /// 任务编号:中餐
 58         /// </summary>
 59         private DbContext()
 60         {
 61             if (string.IsNullOrEmpty(_connectionString))
 62                 throw new ArgumentNullException("数据库连接字符串为空");
 63             _db = new SqlSugarClient(new ConnectionConfig()
 64             {
 65                 ConnectionString = _connectionString,
 66                 DbType = _dbType,
 67                 IsAutoCloseConnection = true,
 68                 IsShardSameThread = true,
 69                 ConfigureExternalServices = new ConfigureExternalServices()
 70                 {
 71                     DataInfoCacheService = new HttpRuntimeCache()
 72                 },
 73                 MoreSettings = new ConnMoreSettings()
 74                 {
 75                     //IsWithNoLockQuery = true,
 76                     IsAutoRemoveDataCache = true
 77                 }
 78             });
 79         }
 80 
 81         /// <summary>
 82         /// 功能描述:构造函数
 83         /// 作  者:beck.huang
 84         /// 创建日期:2018-05-28 17:23:19
 85         /// 任务编号:中餐
 86         /// </summary>
 87         /// <param name="blnIsAutoCloseConnection">是否自动关闭连接</param>
 88         private DbContext(bool blnIsAutoCloseConnection)
 89         {
 90             if (string.IsNullOrEmpty(_connectionString))
 91                 throw new ArgumentNullException("数据库连接字符串为空");
 92             _db = new SqlSugarClient(new ConnectionConfig()
 93             {
 94                 ConnectionString = _connectionString,
 95                 DbType = _dbType,
 96                 IsAutoCloseConnection = blnIsAutoCloseConnection,
 97                 IsShardSameThread = true,
 98                 ConfigureExternalServices = new ConfigureExternalServices()
 99                 {
100                     DataInfoCacheService = new HttpRuntimeCache()
101                 },
102                 MoreSettings = new ConnMoreSettings()
103                 {
104                     //IsWithNoLockQuery = true,
105                     IsAutoRemoveDataCache = true
106                 }
107             });
108         }
109         #endregion
110 
111         #region 实例方法
112         /// <summary>
113         /// 功能描述:获取数据库处理对象
114         /// 作  者:beck.huang
115         /// 创建日期:2018-05-08 09:46:06
116         /// 任务编号:中餐
117         /// </summary>
118         /// <returns>返回值</returns>
119         public SimpleClient<T> GetEntityDB<T>() where T : class,new()
120         {
121             return new SimpleClient<T>(_db);
122         }
123         /// <summary>
124         /// 功能描述:获取数据库处理对象
125         /// 作  者:beck.huang
126         /// 创建日期:2018-05-09 09:17:43
127         /// 任务编号:中餐
128         /// </summary>
129         /// <param name="db">db</param>
130         /// <returns>返回值</returns>
131         public SimpleClient<T> GetEntityDB<T>(SqlSugarClient db) where T : class,new()
132         {
133             return new SimpleClient<T>(db);
134         }
135 
136         #region 根据数据库表生产实体类
137         /// <summary>
138         /// 功能描述:根据数据库表生产实体类
139         /// 作  者:beck.huang
140         /// 创建日期:2018-05-08 10:14:37
141         /// 任务编号:中餐
142         /// </summary>       
143         /// <param name="strPath">实体类存放路径</param>
144         public void CreateClassFileByDBTalbe(string strPath)
145         {
146             CreateClassFileByDBTalbe(strPath, "Km.PosZC");
147         }
148         /// <summary>
149         /// 功能描述:根据数据库表生产实体类
150         /// 作  者:beck.huang
151         /// 创建日期:2018-05-08 10:10:59
152         /// 任务编号:中餐
153         /// </summary>
154         /// <param name="strPath">实体类存放路径</param>
155         /// <param name="strNameSpace">命名空间</param>
156         public void CreateClassFileByDBTalbe(string strPath, string strNameSpace)
157         {
158             CreateClassFileByDBTalbe(strPath, strNameSpace, null);
159         }
160 
161         /// <summary>
162         /// 功能描述:根据数据库表生产实体类
163         /// 作  者:beck.huang
164         /// 创建日期:2018-05-08 10:18:18
165         /// 任务编号:中餐
166         /// </summary>
167         /// <param name="strPath">实体类存放路径</param>
168         /// <param name="strNameSpace">命名空间</param>
169         /// <param name="lstTableNames">生产指定的表</param>
170         public void CreateClassFileByDBTalbe(
171             string strPath,
172             string strNameSpace,
173             string[] lstTableNames)
174         {
175             CreateClassFileByDBTalbe(strPath, strNameSpace, lstTableNames, string.Empty);
176         }
177 
178         /// <summary>
179         /// 功能描述:根据数据库表生产实体类
180         /// 作  者:beck.huang
181         /// 创建日期:2018-05-09 15:38:22
182         /// 任务编号:中餐
183         /// </summary>
184         /// <param name="strPath">实体类存放路径</param>
185         /// <param name="strNameSpace">命名空间</param>
186         /// <param name="lstTableNames">生产指定的表</param>
187         /// <param name="strInterface">实现接口</param>
188         public void CreateClassFileByDBTalbe(
189           string strPath,
190           string strNameSpace,
191           string[] lstTableNames,
192           string strInterface,
193           bool blnSerializable = false)
194         {
195             if (lstTableNames != null && lstTableNames.Length > 0)
196             {
197                 _db.DbFirst.Where(lstTableNames).IsCreateDefaultValue().IsCreateAttribute()
198                     .SettingClassTemplate(p => p = @"
199 {using}
200 
201 namespace {Namespace}
202 {
203     {ClassDescription}{SugarTable}" + (blnSerializable ? "[Serializable]" : "") + @"
204     public partial class {ClassName}" + (string.IsNullOrEmpty(strInterface) ? "" : (" : " + strInterface)) + @"
205     {
206         public {ClassName}()
207         {
208 {Constructor}
209         }
210 {PropertyName}
211     }
212 }
213 ")
214                     .SettingPropertyTemplate(p => p = @"
215             {SugarColumn}
216             public {PropertyType} {PropertyName}
217             {
218                 get
219                 {
220                     return _{PropertyName};
221                 }
222                 set
223                 {
224                     if(_{PropertyName}!=value)
225                     {
226                         base.SetValueCall(" + "\"{PropertyName}\",_{PropertyName}" + @");
227                     }
228                     _{PropertyName}=value;
229                 }
230             }")
231                     .SettingPropertyDescriptionTemplate(p => p = "          private {PropertyType} _{PropertyName};\r\n" + p)
232                     .SettingConstructorTemplate(p => p = "              this._{PropertyName} ={DefaultValue};")
233                     .CreateClassFile(strPath, strNameSpace);
234             }
235             else
236             {
237                 _db.DbFirst.IsCreateAttribute().IsCreateDefaultValue()
238                     .SettingClassTemplate(p => p = @"
239 {using}
240 
241 namespace {Namespace}
242 {
243     {ClassDescription}{SugarTable}" + (blnSerializable ? "[Serializable]" : "") + @"
244     public partial class {ClassName}" + (string.IsNullOrEmpty(strInterface) ? "" : (" : " + strInterface)) + @"
245     {
246         public {ClassName}()
247         {
248 {Constructor}
249         }
250 {PropertyName}
251     }
252 }
253 ")
254                     .SettingPropertyTemplate(p => p = @"
255             {SugarColumn}
256             public {PropertyType} {PropertyName}
257             {
258                 get
259                 {
260                     return _{PropertyName};
261                 }
262                 set
263                 {
264                     if(_{PropertyName}!=value)
265                     {
266                         base.SetValueCall(" + "\"{PropertyName}\",_{PropertyName}" + @");
267                     }
268                     _{PropertyName}=value;
269                 }
270             }")
271                     .SettingPropertyDescriptionTemplate(p => p = "          private {PropertyType} _{PropertyName};\r\n" + p)
272                     .SettingConstructorTemplate(p => p = "              this._{PropertyName} ={DefaultValue};")
273                     .CreateClassFile(strPath, strNameSpace);
274             }
275         }
276         #endregion
277 
278         #region 根据实体类生成数据库表
279         /// <summary>
280         /// 功能描述:根据实体类生成数据库表
281         /// 作  者:beck.huang
282         /// 创建日期:2018-05-08 10:31:02
283         /// 任务编号:中餐
284         /// </summary>
285         /// <param name="blnBackupTable">是否备份表</param>
286         /// <param name="lstEntitys">指定的实体</param>
287         public void CreateTableByEntity<T>(bool blnBackupTable, params T[] lstEntitys) where T : class,new()
288         {
289             Type[] lstTypes = null;
290             if (lstEntitys != null)
291             {
292                 lstTypes = new Type[lstEntitys.Length];
293                 for (int i = 0; i < lstEntitys.Length; i++)
294                 {
295                     T t = lstEntitys[i];
296                     lstTypes[i] = typeof(T);
297                 }
298             }
299             CreateTableByEntity(blnBackupTable, lstTypes);
300         }
301 
302         /// <summary>
303         /// 功能描述:根据实体类生成数据库表
304         /// 作  者:beck.huang
305         /// 创建日期:2018-05-08 10:31:14
306         /// 任务编号:中餐
307         /// </summary>
308         /// <param name="blnBackupTable">是否备份表</param>
309         /// <param name="lstEntitys">指定的实体</param>
310         public void CreateTableByEntity(bool blnBackupTable, params Type[] lstEntitys)
311         {
312             if (blnBackupTable)
313             {
314                 _db.CodeFirst.BackupTable().InitTables(lstEntitys); //change entity backupTable            
315             }
316             else
317             {
318                 _db.CodeFirst.InitTables(lstEntitys);
319             }
320         }
321         #endregion
322 
323         #endregion
324 
325         #region 静态方法
326 
327         /// <summary>
328         /// 功能描述:获得一个DbContext
329         /// 作  者:beck.huang
330         /// 创建日期:2018-05-28 17:24:12
331         /// 任务编号:中餐
332         /// </summary>
333         /// <param name="blnIsAutoCloseConnection">是否自动关闭连接(如果为false,则使用接受时需要手动关闭Db)</param>
334         /// <returns>返回值</returns>
335         public static DbContext GetDbContext(bool blnIsAutoCloseConnection)
336         {
337             return new DbContext(blnIsAutoCloseConnection);
338         }
339 
340         /// <summary>
341         /// 功能描述:设置初始化参数
342         /// 作  者:beck.huang
343         /// 创建日期:2018-05-08 10:02:32
344         /// 任务编号:中餐
345         /// </summary>
346         /// <param name="strConnectionString">连接字符串</param>
347         /// <param name="enmDbType">数据库类型</param>
348         public static void Init(string strConnectionString, DbType enmDbType = SqlSugar.DbType.MySql)
349         {
350             _connectionString = strConnectionString;
351             _dbType = enmDbType;
352         }
353 
354         /// <summary>
355         /// 功能描述:创建一个链接配置
356         /// 作  者:beck.huang
357         /// 创建日期:2018-05-09 09:03:33
358         /// 任务编号:中餐
359         /// </summary>
360         /// <param name="blnIsAutoCloseConnection">是否自动关闭连接</param>
361         /// <param name="blnIsShardSameThread">是否夸类事务</param>
362         /// <returns>ConnectionConfig</returns>
363         public static ConnectionConfig GetConnectionConfig(bool blnIsAutoCloseConnection = true, bool blnIsShardSameThread = false)
364         {
365             ConnectionConfig config = new ConnectionConfig()
366             {
367                 ConnectionString = _connectionString,
368                 DbType = _dbType,
369                 IsAutoCloseConnection = blnIsAutoCloseConnection,
370                 ConfigureExternalServices = new ConfigureExternalServices()
371                 {
372                     DataInfoCacheService = new HttpRuntimeCache()
373                 },
374                 IsShardSameThread = blnIsShardSameThread
375             };
376             return config;
377         }
378 
379         /// <summary>
380         /// 功能描述:获取一个自定义的DB
381         /// 作  者:beck.huang
382         /// 创建日期:2018-05-08 09:49:36
383         /// 任务编号:中餐
384         /// </summary>
385         /// <param name="config">config</param>
386         /// <returns>返回值</returns>
387         public static SqlSugarClient GetCustomDB(ConnectionConfig config)
388         {
389             return new SqlSugarClient(config);
390         }
391         /// <summary>
392         /// 功能描述:获取一个自定义的数据库处理对象
393         /// 作  者:beck.huang
394         /// 创建日期:2018-05-09 08:56:20
395         /// 任务编号:中餐
396         /// </summary>
397         /// <param name="sugarClient">sugarClient</param>
398         /// <returns>返回值</returns>
399         public static SimpleClient<T> GetCustomEntityDB<T>(SqlSugarClient sugarClient) where T : class,new()
400         {
401             return new SimpleClient<T>(sugarClient);
402         }
403         /// <summary>
404         /// 功能描述:获取一个自定义的数据库处理对象
405         /// 作  者:beck.huang
406         /// 创建日期:2018-05-08 09:50:32
407         /// 任务编号:中餐
408         /// </summary>
409         /// <param name="config">config</param>
410         /// <returns>返回值</returns>
411         public static SimpleClient<T> GetCustomEntityDB<T>(ConnectionConfig config) where T : class,new()
412         {
413             SqlSugarClient sugarClient = GetCustomDB(config);
414             return GetCustomEntityDB<T>(sugarClient);
415         }
416         #endregion
417     }
View Code

相关文章: