wanshenmean
2024-11-06 fb77cc8fe39bd3c3f49b336bf9e664957fe2dc07
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 命名空间:WIDESEAWCS_QuartzJob
 * 创建者:胡童庆
 * 创建时间:2024/8/2 16:13:36
 * 版本:V1.0.0
 * 描述:映射QuartzJob数据库表
 *
 * ----------------------------------------------------------------
 * 修改人:
 * 修改时间:
 * 版本:V1.0.1
 * 修改说明:
 * 
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
 
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Core.DB;
using WIDESEAWCS_Core.Helper;
using WIDESEAWCS_Core.Seed;
 
namespace WIDESEAWCS_QuartzJob.Seed
{
    public class QuartzJobCreateDataTabel
    {
        private static string SeedDataFolder = "WIDESEAWCS_DB.DBSeed.Json/{0}.tsv";
 
        /// <summary>
        /// 映射QuartzJob数据库表
        /// </summary>
        /// <param name="dbContext"></param>
        /// <returns></returns>
        public static async Task SeedAsync(DBContext dbContext, string WebRootPath)
        {
            try
            {
                Console.WriteLine("Create QuartzJob Tables...");
 
                var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
                var referencedAssemblies = System.IO.Directory.GetFiles(path, "WIDESEAWCS_QuartzJob.dll").Select(Assembly.LoadFrom).ToArray();
 
                var modelTypes = referencedAssemblies
                    .SelectMany(a => a.DefinedTypes)
                    .Select(type => type.AsType())
                    .Where(x => x.IsClass && x.Namespace is "WIDESEAWCS_QuartzJob.Models" && x.GetCustomAttribute<SugarTable>() != null)
                    .ToList();
                SeedDataFolder = Path.Combine(WebRootPath, SeedDataFolder);
                modelTypes.ForEach(t =>
                {
                    //var diffString = dbContext.Db.CodeFirst.GetDifferenceTables(t).ToDiffString();
                    // 这里只支持添加表,不支持删除
                    // 如果想要删除,数据库直接右键删除,或者联系SqlSugar作者;
                    IDbMaintenance dbMaintenance = dbContext.Db.DbMaintenance;
                    if (!dbMaintenance.IsAnyTable(t.Name, false))
                    {
                        Console.WriteLine(t.Name);
                        dbContext.Db.CodeFirst.InitTables(t);
 
                        string seedData = FileHelper.ReadFile(string.Format(SeedDataFolder, t.Name), Encoding.UTF8);
 
                        #region AddSeedData
                        if (seedData != "不存在相应的目录")
                        {
                            List<Dictionary<string, object>> dicFile = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(seedData);
 
                            if (dicFile.Count > 0)
                            {
                                List<Dictionary<string, object>> dic = new List<Dictionary<string, object>>();
 
                                List<string> columnNames = dbContext.Db.DbMaintenance.GetColumnInfosByTableName(t.Name, false).Select(x => x.DbColumnName).ToList();
                                var a = t.GetProperties().FirstOrDefault(x => !columnNames.Contains(x.Name));
 
                                List<PropertyInfo> propertyInfos = t.GetProperties().Where(x => columnNames.Contains(x.Name)).ToList();
                                for (int j = 0; j < dicFile.Count; j++)
                                {
                                    Dictionary<string, object> keyValuePairs = new Dictionary<string, object>();
                                    for (int i = 0; i < propertyInfos.Count; i++)
                                    {
                                        PropertyInfo propertyInfo = propertyInfos[i];
                                        SugarColumn sugarColumn = propertyInfo.GetCustomAttribute<SugarColumn>();
                                        if (sugarColumn != null)
                                        {
                                            if (!sugarColumn.IsIgnore)
                                            {
                                                keyValuePairs.Add(propertyInfo.Name, dicFile[j][propertyInfo.Name]);
                                            }
                                        }
                                    }
                                    dic.Add(keyValuePairs);
                                }
 
                                if (dic.Count > 0)
                                {
                                    for (int i = 0; i < dic.Count; i++)
                                    {
                                        if (dic[i].ContainsKey("CreateDate"))
                                            dic[i]["CreateDate"] = DateTime.Now;
                                        else
                                            dic[i].Add("CreateDate", DateTime.Now);
                                    }
                                    string str = $"SET IDENTITY_INSERT {t.Name} ON;";
 
                                    str += dbContext.Db.Insertable(dic).AS(t.Name).ToSqlString();
 
                                    str += ($"SET IDENTITY_INSERT {t.Name} OFF;");
 
                                    dbContext.Db.Ado.ExecuteCommand(str);
 
                                    ConsoleHelper.WriteSuccessLine($"Table [{t.Name}] SeedData Added Successfully");
                                }
                            }
                        }
                        #endregion
                    }
                });
                ConsoleHelper.WriteSuccessLine($"QuartzJob Tables Created Successfully!");
                Console.WriteLine();
 
 
            }
            catch (Exception ex)
            {
                // 1、若是Mysql,查看常见问题:https://github.com/anjoy8/Blog.Core/issues/148#issue-776281770
                //2、若是Oracle,查看常见问题:https://github.com/anjoy8/Blog.Core/issues/148#issuecomment-752340231
                throw new Exception("错误:" + ex.Message);
            }
        }
    }
}