zhoufan 3 jaren geleden
bovenliggende
commit
017760953b

+ 0 - 41
Net6Demo_Api.Business/BaseBusiness.cs

@@ -9,7 +9,6 @@ using System.Linq;
9 9
 using System.Reflection;
10 10
 using System.ComponentModel.DataAnnotations;
11 11
 using System.Data.Common;
12
-using MySqlConnector;
13 12
 using Net6Demo_Api.Entity;
14 13
 
15 14
 namespace Net6Demo_Api.Business
@@ -513,46 +512,6 @@ namespace Net6Demo_Api.Business
513 512
             return await _db.ExecuteSqlAsync(sql, paras);
514 513
         }
515 514
 
516
-        /// <summary>
517
-        /// 通过Sql语句查询返回DataSet,参数化查询
518
-        /// </summary>
519
-        /// <param name="sql">Sql语句</param>
520
-        /// <param name="parameters">参数</param>
521
-        /// <returns></returns>
522
-        public DataSet GetDataSetWithSql(string sql, List<DbParameter> parameters = null)
523
-        {
524
-            DbProviderFactory dbProviderFactory = MySqlConnectorFactory.Instance;
525
-            using (DbConnection conn = dbProviderFactory.CreateConnection())
526
-            {
527
-                conn.ConnectionString = _db.ConnectionString;
528
-                if (conn.State != ConnectionState.Open)
529
-                {
530
-                    conn.Open();
531
-                }
532
-
533
-                using (DbCommand cmd = conn.CreateCommand())
534
-                {
535
-                    cmd.Connection = conn;
536
-                    cmd.CommandText = sql;
537
-                    if (parameters != null && parameters.Count > 0)
538
-                    {
539
-                        foreach (var item in parameters)
540
-                        {
541
-                            cmd.Parameters.Add(item);
542
-                        }
543
-                    }
544
-
545
-                    DbDataAdapter adapter = dbProviderFactory.CreateDataAdapter();
546
-                    adapter.SelectCommand = cmd;
547
-                    DataSet ds = new DataSet();
548
-                    adapter.Fill(ds);
549
-                    cmd.Parameters.Clear();
550
-
551
-                    return ds;
552
-                }
553
-            }
554
-        }
555
-
556 515
         #endregion
557 516
 
558 517
         #region 缓存数据

+ 0 - 4
Net6Demo_Api.Business/Net6Demo_Api.Business.csproj

@@ -7,10 +7,6 @@
7 7
   </PropertyGroup>
8 8
 
9 9
   <ItemGroup>
10
-    <PackageReference Include="EFCore.Sharding.MySql" Version="6.0.7" />
11
-  </ItemGroup>
12
-
13
-  <ItemGroup>
14 10
     <ProjectReference Include="..\Net6Demo_Api.Entity\Net6Demo_Api.Entity.csproj" />
15 11
     <ProjectReference Include="..\Net6Demo_Api.IBusiness\Net6Demo_Api.IBusiness.csproj" />
16 12
     <ProjectReference Include="..\Net6Demo_Api.Util\Net6Demo_Api.Util.csproj" />

+ 40 - 0
Net6Demo_Api.Entity/Input/HomeInput.cs

@@ -0,0 +1,40 @@
1
+using System.ComponentModel;
2
+
3
+namespace Net6Demo_Api.Entity
4
+{
5
+    /// <summary>
6
+    /// 代码配置输入
7
+    /// </summary>
8
+    public class CodeInput
9
+    {
10
+        /// <summary>
11
+        /// 模块名
12
+        /// </summary>
13
+        [DefaultValue("")]
14
+        public string modulename { get; set; } = "";
15
+        /// <summary>
16
+        /// 控制器名
17
+        /// </summary>
18
+        [DefaultValue("")]
19
+        public string controllername { get; set; } = "";
20
+        /// <summary>
21
+        /// 表名
22
+        /// </summary>
23
+        [DefaultValue("")]
24
+        public string tablename { get; set; } = "";
25
+    }
26
+
27
+    public class LoginInput
28
+    {
29
+        /// <summary>
30
+        /// 账号
31
+        /// </summary>
32
+        [DefaultValue("")]
33
+        public string usercode { get; set; } = "";
34
+        /// <summary>
35
+        /// 密码
36
+        /// </summary>
37
+        [DefaultValue("")]
38
+        public string password { get; set; } = "";
39
+    }
40
+}

+ 0 - 18
Net6Demo_Api.Entity/Input/LoginInput.cs

@@ -1,18 +0,0 @@
1
-using System.ComponentModel;
2
-
3
-namespace Net6Demo_Api.Entity
4
-{
5
-    public class LoginInput
6
-    {
7
-        /// <summary>
8
-        /// 账号
9
-        /// </summary>
10
-        [DefaultValue("")]
11
-        public string usercode { get; set; } = "";
12
-        /// <summary>
13
-        /// 密码
14
-        /// </summary>
15
-        [DefaultValue("")]
16
-        public string password { get; set; } = "";
17
-    }
18
-}

+ 0 - 8
Net6Demo_Api.IBusiness/IBaseBusiness.cs

@@ -234,14 +234,6 @@ namespace Net6Demo_Api.IBusiness
234 234
         /// <returns></returns>
235 235
         Task<int> ExecuteSqlAsync(string sql, params (string, object)[] paras);
236 236
 
237
-        /// <summary>
238
-        /// 通过Sql语句查询返回DataSet,参数化查询
239
-        /// </summary>
240
-        /// <param name="sql">Sql语句</param>
241
-        /// <param name="parameters">参数</param>
242
-        /// <returns></returns>
243
-        DataSet GetDataSetWithSql(string sql, List<DbParameter> parameters = null);
244
-
245 237
         #endregion
246 238
     }
247 239
 }

+ 1 - 0
Net6Demo_Api.Util/Extention/Services.cs

@@ -64,6 +64,7 @@ namespace Net6Demo_Api.Util
64 64
                         {
65 65
                             services.Add(new ServiceDescriptor(i, aType, aMap.Value));
66 66
                         });
67
+                        services.Add(new ServiceDescriptor(aType, aType, aMap.Value));
67 68
                     }
68 69
                 });
69 70
             });

+ 698 - 0
Net6Demo_Api.Util/Helper/CreateCodeFileHelper.cs

@@ -0,0 +1,698 @@
1
+using EFCore.Sharding;
2
+using Microsoft.Data.SqlClient;
3
+using Microsoft.Extensions.Hosting;
4
+using MySqlConnector;
5
+using Npgsql;
6
+using Oracle.ManagedDataAccess.Client;
7
+using System.Data;
8
+using System.Data.Common;
9
+using System.Net;
10
+using System.Text;
11
+
12
+namespace Net6Demo_Api.Util
13
+{
14
+    public class CreateCodeFileHelper: ITransientDependency
15
+    {
16
+        private readonly IDbAccessor _db;
17
+        private readonly IHostEnvironment _env;
18
+        private readonly DbProviderFactory _factory;
19
+        private string _key;
20
+        public CreateCodeFileHelper(IDbAccessor db, IHostEnvironment env)
21
+        {
22
+            _db = db;
23
+            _env = env;
24
+
25
+            switch (db.DbType)
26
+            {
27
+                case DatabaseType.SqlServer: _factory = SqlClientFactory.Instance; break;
28
+                case DatabaseType.MySql: _factory = MySqlConnectorFactory.Instance; break;
29
+                case DatabaseType.PostgreSql: _factory = NpgsqlFactory.Instance; break;
30
+                case DatabaseType.Oracle: _factory = OracleClientFactory.Instance; break;
31
+
32
+                default: throw new Exception("此数据库不支持!");
33
+            }
34
+        }
35
+
36
+        /// <summary>
37
+        /// 生成代码文件
38
+        /// </summary>
39
+        /// <param name="tableName"></param>
40
+        public void CreateCodeFile(string tableName, string controllerName, string moduleName)
41
+        {
42
+            var list= GetDataTableWithSql(DbTableSqlDic[_db.DbType]).ToJson().ToObject<List<TableInfo>>();
43
+            if (!string.IsNullOrEmpty(tableName)) list = list.Where(p => p.Name.ToLower() == tableName.ToLower()).ToList();
44
+            foreach (var item in list)
45
+            {
46
+                CreateEntityFile(item.Name,item.Description, controllerName, moduleName);
47
+                CreateBusinessFile(item.Name, controllerName, moduleName);
48
+                CreateControllerFile(item.Name, controllerName, moduleName);
49
+            }
50
+        }
51
+
52
+        /// <summary>
53
+        /// 生成实体文件
54
+        /// </summary>
55
+        public void CreateEntityFile(string tableName, string tableDescription, string controllerName, string moduleName)
56
+        {
57
+            moduleName = string.IsNullOrEmpty(moduleName) ? "" : moduleName + "\\";
58
+            string path = Directory.GetParent(_env.ContentRootPath).Parent.FullName;
59
+            string pname = _env.ApplicationName;
60
+
61
+            var dbtype = _db.DbType;
62
+            var columns = GetDataTableWithSql(DbTableColumnSqlDic[dbtype], new Dictionary<string, string>() { { "@tablename" , tableName } } ).ToJson().ToObject<List<TableColumn>>();
63
+            int index = 0;
64
+            string properties = string.Empty;
65
+            string inputproperties = string.Empty;
66
+            string viewproperties = string.Empty;
67
+            foreach (var column in columns)
68
+            {
69
+                string key = string.Empty;
70
+                if (column.IsKey)
71
+                {
72
+                    key = $@"
73
+        [Key, Column(Order = {index + 1})]";
74
+                    _key = column.Name;
75
+                }
76
+
77
+                Type type = DbTypeToCsharpType(column.Type);
78
+                string isNullable = column.IsNullable && type.IsValueType ? "?" : "";
79
+                string description =string.IsNullOrEmpty(column.Description) ? column.Name : column.Description;
80
+                properties += $@"
81
+        /// <summary>{description}</summary>{key}
82
+        public {type.Name}{isNullable} {column.Name} {{ get; set; }}
83
+";
84
+                inputproperties += $@"
85
+        /// <summary>{description}</summary>
86
+        public {type.Name}{isNullable} {(column.Name.StartsWith("F_")? column.Name.Substring(2) : column.Name)} {{ get; set; }}
87
+";
88
+                viewproperties += $@"
89
+        /// <summary>{description}</summary>
90
+        public {type.Name}{isNullable} {(column.Name.StartsWith("F_") ? column.Name.Substring(2) : column.Name)} {{ get; set; }}
91
+";
92
+                index++;
93
+            }
94
+
95
+            string entityContent = $@"
96
+using System.ComponentModel.DataAnnotations;
97
+using System.ComponentModel.DataAnnotations.Schema;
98
+namespace {pname}.Entity
99
+{{
100
+    /// <summary>
101
+    /// {tableDescription}
102
+    /// </summary>
103
+    [Table(""{tableName}"")]
104
+    public class {tableName}
105
+    {{
106
+        {properties}
107
+    }}
108
+}}";
109
+            CreateFile($@"{path}\{pname}.Entity\DataBase\{moduleName}\{tableName}.cs", entityContent);
110
+
111
+            string inputEntityContent = $@"
112
+using Net6Demo_Api.Util;
113
+namespace {pname}.Entity
114
+{{
115
+    /// <summary>
116
+    /// {tableDescription}
117
+    /// </summary>
118
+    [Map(typeof({tableName}))]
119
+    public class {controllerName}Input
120
+    {{
121
+        {inputproperties}
122
+    }}
123
+}}";
124
+            CreateFile($@"{path}\{pname}.Entity\Input\{moduleName}\{controllerName}Input.cs", inputEntityContent);
125
+
126
+            string viewEntityContent = $@"
127
+using Net6Demo_Api.Util;
128
+namespace {pname}.Entity
129
+{{
130
+    /// <summary>
131
+    /// {tableDescription}
132
+    /// </summary>
133
+    [Map(typeof({tableName}))]
134
+    public class {controllerName}View
135
+    {{
136
+        {viewproperties}
137
+    }}
138
+}}";
139
+            CreateFile($@"{path}\{pname}.Entity\View\{moduleName}\{controllerName}View.cs", viewEntityContent);
140
+
141
+            //数据库类型转C#类型
142
+            Type DbTypeToCsharpType(string dbTypeStr)
143
+            {
144
+                string _dbTypeStr = dbTypeStr.ToLower();
145
+                Type type = null;
146
+                if (DbTypeDic[dbtype].ContainsKey(_dbTypeStr))
147
+                    type = DbTypeDic[dbtype][_dbTypeStr];
148
+                else
149
+                    type = typeof(string);
150
+
151
+                return type;
152
+            }
153
+        }
154
+
155
+        /// <summary>
156
+        /// 生成控制器文件
157
+        /// </summary>
158
+        /// <param name="tableName"></param>
159
+        /// <param name="controllerName"></param>
160
+        /// <param name="moduleName"></param>
161
+        public void CreateControllerFile(string tableName, string controllerName, string moduleName)
162
+        {
163
+            moduleName = string.IsNullOrEmpty(moduleName) ? "" : moduleName + "\\";
164
+            string path = _env.ContentRootPath + "\\Controllers\\" + moduleName;
165
+            string pname = _env.ApplicationName;
166
+
167
+            string controllerContent = $@"
168
+using AutoMapper;
169
+using LinqKit;
170
+using Microsoft.AspNetCore.Http;
171
+using Microsoft.AspNetCore.Mvc;
172
+using Microsoft.EntityFrameworkCore;
173
+using {pname}.Entity;
174
+using {pname}.IBusiness;
175
+namespace {pname}.Controllers
176
+{{
177
+    public class {controllerName}Controller : BaseController
178
+    {{
179
+        private readonly I{controllerName}Business _{controllerName}Bus;
180
+        private readonly IMapper _mapper;
181
+        public {controllerName}Controller(I{controllerName}Business {controllerName}Bus,  IMapper mapper)
182
+        {{
183
+            _{controllerName}Bus = {controllerName}Bus;
184
+            _mapper = mapper;
185
+        }}
186
+        /// <summary>
187
+        /// 获取分页列表
188
+        /// </summary>
189
+        /// <param name=""input""></param>
190
+        /// <returns></returns>
191
+        [HttpPost]
192
+        public async Task<ActionResult> GetDataListPage(PageInput<{controllerName}Input> input)
193
+        {{
194
+            var q = PredicateBuilder.New<{tableName}>(true);
195
+            var data = await _{controllerName}Bus.GetListPageAsync(input, q, p => p.OrderByDescending(q => q.{_key}));
196
+            return Success(""成功"", _mapper.Map<List<{controllerName}View>>(data.Item1), data.Item2);
197
+        }}
198
+        /// <summary>
199
+        /// 获取单个
200
+        /// </summary>
201
+        /// <param name=""id"">主键ID</param>
202
+        /// <returns></returns>
203
+        [HttpGet]
204
+        public async Task<ActionResult> GetData(int id)
205
+        {{
206
+            var data = await _{controllerName}Bus.GetEntityAsync(id);
207
+            if (data != null) return Success(""成功"", _mapper.Map<{controllerName}View>(data));
208
+            else return Error(""获取失败"");
209
+        }}
210
+        /// <summary>
211
+        /// 新增
212
+        /// </summary>
213
+        /// <param name=""input"" ></param>
214
+        /// <returns></returns>
215
+        [HttpPost]
216
+        public async Task<ActionResult> AddData({controllerName}Input input)
217
+        {{
218
+            {tableName} model = _mapper.Map<{tableName}>(input);
219
+            int result = await _{controllerName}Bus.InsertAsync(model);
220
+            if (result > 0) return Success(""成功"");
221
+            else return Error(""失败"");
222
+        }}
223
+        /// <summary>
224
+        /// 编辑
225
+        /// </summary>
226
+        /// <param name=""input"" ></param>
227
+        /// <returns></returns>
228
+        [HttpPost]
229
+        public async Task<ActionResult> EditData({controllerName}Input input)
230
+        {{
231
+            int result = 0;
232
+            var oldData = await _{controllerName}Bus.GetEntityAsync(input.{(_key.StartsWith("F_") ? _key.Substring(2) : _key)});
233
+            if (oldData != null)
234
+            {{
235
+                _mapper.Map(input, oldData);
236
+                result = await _{controllerName}Bus.UpdateAsync(oldData);
237
+            }}
238
+            if (result > 0) return Success(""成功"");
239
+            else return Error(""失败""); 
240
+        }}
241
+        /// <summary>
242
+        /// 删除
243
+        /// </summary>
244
+        /// <param name=""ids"" ></param>
245
+        /// <returns></returns>
246
+        [HttpPost]
247
+        public async Task<ActionResult> DeleteData(List<string> ids)
248
+        {{
249
+            if (await _{controllerName}Bus.DeleteAsync(ids) > 0) return Success(""删除成功"");
250
+            else return Error(""删除失败"");
251
+        }}
252
+        
253
+    }}
254
+}}
255
+";
256
+            CreateFile($@"{path}\{controllerName}Controller.cs", controllerContent);
257
+        }
258
+
259
+        /// <summary>
260
+        /// 生成业务文件
261
+        /// </summary>
262
+        /// <param name="tableName"></param>
263
+        /// <param name="controllerName"></param>
264
+        /// <param name="moduleName"></param>
265
+        public void CreateBusinessFile(string tableName, string controllerName, string moduleName)
266
+        {
267
+            moduleName = string.IsNullOrEmpty(moduleName) ? "" : moduleName + "\\";
268
+            string path = Directory.GetParent(_env.ContentRootPath).Parent.FullName;
269
+            string pname = _env.ApplicationName;
270
+
271
+            string iBusinessContent = $@"
272
+using {pname}.Entity;
273
+namespace {pname}.IBusiness
274
+{{
275
+    public interface I{controllerName}Business : IBaseBusiness<{tableName}>
276
+    {{
277
+        
278
+    }}
279
+}}
280
+";
281
+            CreateFile($@"{path}\{pname}.IBusiness\{moduleName}I{controllerName}Business.cs", iBusinessContent);
282
+
283
+            string businessContent = $@"
284
+using EFCore.Sharding;
285
+using Microsoft.Extensions.Caching.Distributed;
286
+using {pname}.Entity;
287
+using {pname}.IBusiness;
288
+using {pname}.Util;
289
+namespace {pname}.Business
290
+{{
291
+    public class {controllerName}Business : BaseBusiness<{tableName}>, I{controllerName}Business, ITransientDependency
292
+    {{
293
+        public {controllerName}Business(IDbAccessor db, IDistributedCache cache) : base(db, cache, true)
294
+        {{
295
+        }}
296
+    }}
297
+}}
298
+";
299
+            CreateFile($@"{path}\{pname}.Business\{moduleName}{controllerName}Business.cs", businessContent);
300
+        }
301
+
302
+        /// <summary>
303
+        /// 创建文件
304
+        /// </summary>
305
+        /// <param name="filepath"></param>
306
+        /// <param name="content"></param>
307
+        private void CreateFile(string filepath, string content)
308
+        {
309
+            string path = filepath.Substring(0, filepath.LastIndexOf("\\"));
310
+            if (!Directory.Exists(path)) Directory.CreateDirectory(path);
311
+            if (!File.Exists(filepath))
312
+            {
313
+                FileInfo file = new FileInfo(filepath);
314
+                using (FileStream stream = file.Create())
315
+                {
316
+                    using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
317
+                    {
318
+                        writer.Write(content);
319
+                        writer.Flush();
320
+                    }
321
+                }
322
+            }
323
+        }
324
+
325
+        /// <summary>
326
+        /// 根据sql获取DataTable
327
+        /// </summary>
328
+        /// <param name="sql"></param>
329
+        /// <param name="parameters"></param>
330
+        /// <returns></returns>
331
+        private DataTable GetDataTableWithSql(string sql, Dictionary<string, string> paras = null)
332
+        {
333
+            using (DbConnection conn = _factory.CreateConnection())
334
+            {
335
+                conn.ConnectionString = _db.ConnectionString;
336
+                if (conn.State != ConnectionState.Open)
337
+                {
338
+                    conn.Open();
339
+                }
340
+
341
+                using (DbCommand cmd = conn.CreateCommand())
342
+                {
343
+
344
+                    cmd.Connection = conn;
345
+                    cmd.CommandText = sql;
346
+
347
+                    if (paras != null)
348
+                    {
349
+                        foreach (KeyValuePair<string, string> kvp in paras)
350
+                        {
351
+                            switch (_db.DbType)
352
+                            {
353
+                                case DatabaseType.SqlServer: cmd.Parameters.Add(new SqlParameter(kvp.Key, kvp.Value)); break;
354
+                                case DatabaseType.MySql: cmd.Parameters.Add(new MySqlParameter(kvp.Key, kvp.Value)); break;
355
+                                case DatabaseType.PostgreSql: cmd.Parameters.Add(new NpgsqlParameter(kvp.Key, kvp.Value)); break;
356
+                                case DatabaseType.Oracle: cmd.Parameters.Add(new OracleParameter(kvp.Key, kvp.Value)); break;
357
+                            }
358
+                        }
359
+                    }
360
+
361
+                    DbDataAdapter adapter = _factory.CreateDataAdapter();
362
+                    adapter.SelectCommand = cmd;
363
+                    DataSet table = new DataSet();
364
+                    adapter.Fill(table);
365
+                    cmd.Parameters.Clear();
366
+
367
+                    return table.Tables[0];
368
+                }
369
+            }
370
+        }
371
+
372
+        /// <summary>
373
+        /// 数据库类型和C#类型字典
374
+        /// </summary>
375
+        private Dictionary<DatabaseType, Dictionary<string, Type>> DbTypeDic = new Dictionary<DatabaseType, Dictionary<string, Type>>()
376
+        {
377
+            { DatabaseType.SqlServer,new Dictionary<string, Type>()
378
+                {
379
+                    { "int", typeof(Int32) },
380
+                    { "text", typeof(string) },
381
+                    { "bigint", typeof(Int64) },
382
+                    { "binary", typeof(byte[]) },
383
+                    { "bit", typeof(bool) },
384
+                    { "char", typeof(string) },
385
+                    { "date", typeof(DateTime) },
386
+                    { "datetime", typeof(DateTime) },
387
+                    { "datetime2", typeof(DateTime) },
388
+                    { "datetimeoffset", typeof(DateTimeOffset) },
389
+                    { "decimal", typeof(decimal) },
390
+                    { "float", typeof(double) },
391
+                    { "image", typeof(byte[]) },
392
+                    { "money", typeof(decimal) },
393
+                    { "nchar", typeof(string) },
394
+                    { "ntext", typeof(string) },
395
+                    { "numeric", typeof(decimal) },
396
+                    { "nvarchar", typeof(string) },
397
+                    { "real", typeof(Single) },
398
+                    { "smalldatetime", typeof(DateTime) },
399
+                    { "smallint", typeof(Int16) },
400
+                    { "smallmoney", typeof(decimal) },
401
+                    { "time", typeof(TimeSpan) },
402
+                    { "timestamp", typeof(DateTime) },
403
+                    { "tinyint", typeof(byte) },
404
+                    { "varbinary", typeof(byte[]) },
405
+                    { "varchar", typeof(string) },
406
+                    { "variant", typeof(object) },
407
+                    { "uniqueidentifier", typeof(Guid) }
408
+                }
409
+            },
410
+            { DatabaseType.MySql,new Dictionary<string, Type>()
411
+                {
412
+                    { "bool",typeof(bool)},
413
+                    { "boolean",typeof(bool)},
414
+                    { "bit(1)",typeof(bool)},
415
+                    { "binary",typeof(byte[])},
416
+                    { "varbinary",typeof(byte[])},
417
+                    { "blob",typeof(byte[])},
418
+                    { "longblob",typeof(byte[])},
419
+                    { "date",typeof(DateTime)},
420
+                    { "datetime",typeof(DateTime)},
421
+                    { "timestamp",typeof(DateTime)},
422
+                    { "datetimeoffset", typeof(DateTimeOffset) },
423
+                    { "time", typeof(TimeSpan) },
424
+                    { "double",typeof(double)},
425
+                    { "smallint",typeof(Int16)},
426
+                    { "int",typeof(Int32)},
427
+                    { "bigint",typeof(Int64)},
428
+                    { "tinyint",typeof(bool)},
429
+                    { "float",typeof(float)},
430
+                    { "decimal",typeof(decimal)},
431
+                    { "numeric",typeof(decimal)},
432
+                    { "char",typeof(string)},
433
+                    { "nchar",typeof(string)},
434
+                    { "varchar",typeof(string)},
435
+                    { "nvarchar",typeof(string)},
436
+                    { "text",typeof(string)},
437
+                    { "longtext",typeof(string)}
438
+                }
439
+            },
440
+            { DatabaseType.PostgreSql,new Dictionary<string, Type>()
441
+                {
442
+                    { "bool", typeof(bool) },
443
+                    { "boolean",typeof(bool)},
444
+                    { "int2", typeof(Int16) },
445
+                    { "smallint", typeof(Int16) },
446
+                    { "int4", typeof(Int32) },
447
+                    { "bigint", typeof(Int64) },
448
+                    { "int8", typeof(Int64) },
449
+                    { "integer", typeof(Int32) },
450
+                    { "float4", typeof(float) },
451
+                    { "float8", typeof(decimal) },
452
+                    { "decimal", typeof(decimal) },
453
+                    { "numeric", typeof(decimal) },
454
+                    { "money", typeof(decimal) },
455
+                    { "text", typeof(string) },
456
+                    { "varchar", typeof(string) },
457
+                    { "bpchar", typeof(string) },
458
+                    { "citext", typeof(string) },
459
+                    { "json", typeof(string) },
460
+                    { "jsonb", typeof(string) },
461
+                    { "xml", typeof(string) },
462
+                    { "bit(1)", typeof(bool) },
463
+                    { "uuid", typeof(Guid) },
464
+                    { "inet", typeof(IPAddress) },
465
+                    { "date", typeof(DateTime) },
466
+                    { "interval", typeof(TimeSpan) },
467
+                    { "timestamp", typeof(DateTime) },
468
+                    { "timestamptz", typeof(DateTime) },
469
+                    { "time", typeof(TimeSpan) },
470
+                    { "timetz", typeof(DateTimeOffset) },
471
+                    { "bytea", typeof(byte[]) },
472
+                    { "oid", typeof(uint) },
473
+                    { "xid", typeof(uint) },
474
+                    { "cid", typeof(uint) },
475
+                    { "name", typeof(string) }
476
+                }
477
+            },
478
+            { DatabaseType.Oracle,new Dictionary<string, Type>()
479
+                {
480
+                    { "boolean",typeof(bool)},
481
+                    { "bfile", typeof(byte[]) },
482
+                    { "blob", typeof(byte[]) },
483
+                    { "char", typeof(string) },
484
+                    { "clob", typeof(string) },
485
+                    { "date", typeof(DateTime) },
486
+                    { "float", typeof(decimal) },
487
+                    { "integer", typeof(decimal) },
488
+                    { "long", typeof(string) },
489
+                    { "long raw", typeof(string[]) },
490
+                    { "nchar", typeof(string) },
491
+                    { "nclob", typeof(string) },
492
+                    { "number", typeof(decimal) },
493
+                    { "nvarchar2", typeof(string) },
494
+                    { "raw", typeof(byte[]) },
495
+                    { "rowid", typeof(string) },
496
+                    { "timestamp", typeof(DateTime) },
497
+                    { "unsigned integer", typeof(decimal) },
498
+                    { "varchar2", typeof(string) }
499
+                }
500
+            },
501
+            { DatabaseType.SQLite,new Dictionary<string, Type>()
502
+                {
503
+                    { "tinyint", typeof(byte) },
504
+                    { "bool", typeof(bool) },
505
+                    { "boolean",typeof(bool)},
506
+                    { "int16", typeof(Int16) },
507
+                    { "smallint", typeof(Int16) },
508
+                    { "int32", typeof(Int32) },
509
+                    { "int", typeof(Int32) },
510
+                    { "int64", typeof(Int64) },
511
+                    { "integer", typeof(Int64) },
512
+                    { "text", typeof(string) },
513
+                    { "bigint", typeof(Int64) },
514
+                    { "real", typeof(double) },
515
+                    { "numeric", typeof(decimal) },
516
+                    { "decimal", typeof(decimal) },
517
+                    { "money", typeof(decimal) },
518
+                    { "currency", typeof(decimal) },
519
+                    { "date", typeof(DateTime) },
520
+                    { "smalldate", typeof(DateTime) },
521
+                    { "datetime", typeof(DateTime) },
522
+                    { "time", typeof(TimeSpan) },
523
+                    { "ntext", typeof(string) },
524
+                    { "char", typeof(string) },
525
+                    { "nchar", typeof(string) },
526
+                    { "varchar", typeof(string) },
527
+                    { "nvarchar", typeof(string) },
528
+                    { "string", typeof(string) },
529
+                    { "binary", typeof(byte[]) },
530
+                    { "blob", typeof(byte[]) },
531
+                    { "varbinary", typeof(byte[]) },
532
+                    { "image", typeof(byte[]) },
533
+                    { "general", typeof(byte[]) },
534
+                    { "datetimeoffset", typeof(DateTimeOffset) },
535
+                    { "guid", typeof(Guid) }
536
+                }
537
+            }
538
+        };
539
+
540
+        /// <summary>
541
+        /// 数据库类型表sql字典
542
+        /// </summary>
543
+        private Dictionary<DatabaseType, string> DbTableSqlDic=new Dictionary<DatabaseType, string>()
544
+        {
545
+            { DatabaseType.SqlServer,
546
+                "select [Name] = a.name, [Description] = g.value from sys.tables a left join sys.extended_properties g on (a.object_id = g.major_id AND g.minor_id = 0 AND g.name= 'MS_Description')"
547
+            },
548
+            { DatabaseType.MySql,
549
+                "SELECT TABLE_NAME as Name,table_comment as Description FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA =(select database())"
550
+            },
551
+            { DatabaseType.Oracle,
552
+                "SELECT A.TABLE_NAME AS NAME, B.comments AS DESCRIPTION FROM USER_TABLES A, USER_TAB_COMMENTS B WHERE A.table_name = B.table_name(+)"
553
+            },
554
+            { DatabaseType.PostgreSql,
555
+                "select relname as Name, cast(obj_description(relfilenode,'pg_class') as varchar) as Description from pg_class c where relkind = 'r' and relname not like 'pg_%' and relname not order by relname"
556
+            },
557
+            { DatabaseType.SQLite,""},
558
+        };
559
+
560
+        /// <summary>
561
+        /// 数据库类型表字段sql字典
562
+        /// </summary>
563
+        private Dictionary<DatabaseType, string> DbTableColumnSqlDic = new Dictionary<DatabaseType, string>()
564
+        {
565
+            { DatabaseType.SqlServer,
566
+                @"
567
+select
568
+sys.columns.name as [Name],
569
+sys.types.name as [Type], 
570
+sys.columns.is_nullable [IsNullable], 
571
+[IsIdentity]=CONVERT(BIT, (select count(*) from sys.identity_columns where sys.identity_columns.object_id = sys.columns.object_id and sys.columns.column_id = sys.identity_columns.column_id)),
572
+(select value from sys.extended_properties where sys.extended_properties.major_id = sys.columns.object_id and sys.extended_properties.minor_id = sys.columns.column_id and name='MS_Description') as [Description],
573
+[IsKey] =CONVERT(bit,(case when sys.columns.name in (select b.column_name
574
+from information_schema.table_constraints a
575
+inner join information_schema.constraint_column_usage b
576
+on a.constraint_name = b.constraint_name
577
+where a.constraint_type = 'PRIMARY KEY' and a.table_name = @tablename) then 1 else 0 end))
578
+from sys.columns, sys.tables, sys.types where sys.columns.object_id = sys.tables.object_id and sys.columns.system_type_id=sys.types.system_type_id and sys.tables.name=@tablename and sys.types.name !='sysname' 
579
+order by sys.columns.column_id asc;"
580
+            },
581
+            { DatabaseType.MySql,
582
+                @"
583
+select DISTINCT
584
+a.COLUMN_NAME as Name,
585
+a.DATA_TYPE as Type,
586
+(a.COLUMN_KEY = 'PRI') as IsKey,
587
+(a.IS_NULLABLE = 'YES') as IsNullable,
588
+a.COLUMN_COMMENT as Description,
589
+a.ORDINAL_POSITION
590
+from information_schema.columns a 
591
+where table_name=@tableName and table_schema=(select database())
592
+ORDER BY a.ORDINAL_POSITION;"
593
+            },
594
+            { DatabaseType.Oracle,
595
+                @"
596
+SELECT 
597
+A.COLUMN_NAME AS NAME,
598
+A.DATA_TYPE   AS TYPE,
599
+NVL2(D.CONSTRAINT_TYPE,1,0) AS ISKEY,
600
+DECODE(A.NULLABLE,'Y',1,0) AS ISNULLABLE,
601
+B.COMMENTS AS DESCRIPTION
602
+FROM USER_TAB_COLUMNS A, USER_COL_COMMENTS B, USER_IND_COLUMNS C, USER_CONSTRAINTS D
603
+WHERE A.TABLE_NAME = B.TABLE_NAME(+)
604
+AND A.COLUMN_NAME = B.COLUMN_NAME(+)
605
+AND A.TABLE_NAME = C.TABLE_NAME(+)
606
+AND A.COLUMN_NAME = C.COLUMN_NAME(+)
607
+AND C.INDEX_NAME = D.INDEX_NAME(+)
608
+AND 'P' = D.CONSTRAINT_TYPE(+)
609
+AND A.TABLE_NAME= :tableName
610
+ORDER BY A.COLUMN_ID;"
611
+            },
612
+            { DatabaseType.PostgreSql,
613
+                @"
614
+SELECT 
615
+a.attname as Name,
616
+pg_type.typname as Type,
617
+(SELECT count(1) from(SELECT ic.column_name as ColumnName FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage AS ccu USING(constraint_schema, constraint_name) JOIN information_schema.columns AS ic ON ic.table_schema = tc.constraint_schema AND tc.table_name = ic.table_name AND ccu.column_name = ic.column_name
618
+where constraint_type = 'PRIMARY KEY' and tc.table_name = @tablename) KeyA WHERE KeyA.ColumnName = a.attname)> 0 as IsKey,
619
+a.attnotnull<> True as IsNullable,
620
+col_description(a.attrelid, a.attnum) as Description
621
+FROM pg_class as c,pg_attribute as a inner join pg_type on pg_type.oid = a.atttypid
622
+where c.relname = @tablename and a.attrelid = c.oid and a.attnum > 0
623
+order by a.attnum asc;"
624
+            }
625
+        };
626
+
627
+        /// <summary>
628
+        /// 表信息
629
+        /// </summary>
630
+        private class TableInfo
631
+        {
632
+            /// <summary>
633
+            /// 表名
634
+            /// </summary>
635
+            public string Name { get; set; }
636
+
637
+            /// <summary>
638
+            /// 表描述说明
639
+            /// </summary>
640
+            public string Description
641
+            {
642
+                get
643
+                {
644
+                    return string.IsNullOrEmpty(_description) ? Name : _description;
645
+                }
646
+                set
647
+                {
648
+                    _description = value;
649
+                }
650
+            }
651
+
652
+            private string _description { get; set; }
653
+        }
654
+
655
+        /// <summary>
656
+        /// 表结构信息
657
+        /// </summary>
658
+        private class TableColumn
659
+        {
660
+            /// <summary>
661
+            /// 字段名
662
+            /// </summary>
663
+            public string Name { get; set; }
664
+
665
+            /// <summary>
666
+            /// 字段类型
667
+            /// </summary>
668
+            public string Type { get; set; }
669
+
670
+            /// <summary>
671
+            /// 是否为主键
672
+            /// </summary>
673
+            public bool IsKey { get; set; }
674
+
675
+            /// <summary>
676
+            /// 是否为空
677
+            /// </summary>
678
+            public bool IsNullable { get; set; }
679
+
680
+            /// <summary>
681
+            /// 字段描述说明
682
+            /// </summary>
683
+            public string Description
684
+            {
685
+                get
686
+                {
687
+                    return string.IsNullOrEmpty(_description) ? Name : _description;
688
+                }
689
+                set
690
+                {
691
+                    _description = value;
692
+                }
693
+            }
694
+
695
+            private string _description { get; set; }
696
+        }
697
+    }
698
+}

+ 4 - 0
Net6Demo_Api.Util/Net6Demo_Api.Util.csproj

@@ -8,6 +8,10 @@
8 8
 
9 9
   <ItemGroup>
10 10
     <PackageReference Include="AutoMapper" Version="11.0.1" />
11
+    <PackageReference Include="EFCore.Sharding.MySql" Version="6.0.7" />
12
+    <PackageReference Include="EFCore.Sharding.Oracle" Version="6.0.7" />
13
+    <PackageReference Include="EFCore.Sharding.PostgreSql" Version="6.0.7" />
14
+    <PackageReference Include="EFCore.Sharding.SqlServer" Version="6.0.7" />
11 15
     <PackageReference Include="Microsoft.Extensions.Http" Version="6.0.0" />
12 16
     <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
13 17
     <PackageReference Include="NLog.Web.AspNetCore" Version="5.1.0" />

+ 15 - 1
Net6Demo_Api/Controllers/HomeController.cs

@@ -22,13 +22,15 @@ namespace Net6Demo_Api.Controllers
22 22
         private readonly IUserAccountBusiness _userBus;
23 23
         private readonly HttpHelper _httpHelper;
24 24
         private readonly IWebHostEnvironment _env;
25
+        private readonly CreateCodeFileHelper _createHelper;
25 26
         private readonly ILogger _logger;
26
-        public HomeController(IUserAccountBusiness userBus, IConfiguration config, HttpHelper httpHelper, IWebHostEnvironment env,ILogger<HomeController> logger)
27
+        public HomeController(IUserAccountBusiness userBus, IConfiguration config, HttpHelper httpHelper, IWebHostEnvironment env, CreateCodeFileHelper createHelper,ILogger<HomeController> logger)
27 28
         {
28 29
             _userBus = userBus;
29 30
             _config = config;
30 31
             _httpHelper = httpHelper;
31 32
             _env = env;
33
+            _createHelper=createHelper;
32 34
             _logger = logger;
33 35
         }
34 36
 
@@ -86,6 +88,18 @@ namespace Net6Demo_Api.Controllers
86 88
         }
87 89
 
88 90
         /// <summary>
91
+        /// 生成代码文件(只支持SqlServer,MySql,Oracle,PostgreSql)
92
+        /// </summary>
93
+        /// <param name="input"></param>
94
+        /// <returns></returns>
95
+        [HttpPost]
96
+        public ActionResult BulidCodeFile(CodeInput input)
97
+        {
98
+            _createHelper.CreateCodeFile(input.tablename, input.controllername, input.modulename);
99
+            return Success("成功");
100
+        }
101
+
102
+        /// <summary>
89 103
         /// 登录
90 104
         /// </summary>
91 105
         /// <param name="input">登录信息</param>