1
z8018
2025-03-12 17e4c7e3e7b3ef60d9da6de3b2a39a14a53c38a0
WIDESEAWCS_Server/WIDESEAWCS_Core/Seed/DBSeed.cs
@@ -1,6 +1,8 @@
using Castle.Components.DictionaryAdapter.Xml;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Text;
using SkiaSharp;
using SqlSugar;
using System;
using System.Collections.Generic;
@@ -10,6 +12,7 @@
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WIDESEAWCS_Core.Attributes;
using WIDESEAWCS_Core.Const;
using WIDESEAWCS_Core.DB;
using WIDESEAWCS_Core.Helper;
@@ -40,7 +43,7 @@
                Console.WriteLine("************ WIDESEA DataBase Set *****************");
                Console.WriteLine($"Master DB ConId: {DBContext.ConnId}");
                //Console.WriteLine($"Master DB ConId: {DBContext.ConnId}");
                Console.WriteLine($"Master DB Type: {DBContext.DbType}");
                //Console.WriteLine($"Master DB ConnectString: {DBContext.ConnectionString}");
@@ -52,7 +55,7 @@
                if (DBContext.DbType != SqlSugar.DbType.Oracle)
                {
                    dbContext.Db.DbMaintenance.CreateDatabase();
                    ConsoleHelper.WriteSuccessLine($"Database created successfully!");
                    ConsoleHelper.WriteSuccessLine($"Database Created Successfully!");
                }
                else
                {
@@ -64,10 +67,10 @@
                // 注意不要把其他命名空间下的也添加进来。
                Console.WriteLine("Create Tables...");
                var path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
                var referencedAssemblies = System.IO.Directory.GetFiles(path, MainDb.AssemblyName).Select(Assembly.LoadFrom).ToArray();
                string path = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
                Assembly[] referencedAssemblies = System.IO.Directory.GetFiles(path, MainDb.AssemblyName).Select(Assembly.LoadFrom).ToArray();
                var modelTypes = referencedAssemblies
                List<Type> modelTypes = referencedAssemblies
                    .SelectMany(a => a.DefinedTypes)
                    .Select(type => type.AsType())
                    .Where(x => x.IsClass && x.Namespace is MainDb.EntityNameSpace && x.GetCustomAttribute<SugarTable>() != null)
@@ -81,27 +84,82 @@
                    IDbMaintenance dbMaintenance = dbContext.Db.DbMaintenance;
                    if (!dbMaintenance.IsAnyTable(t.Name, false))
                    {
                        Console.WriteLine(t.Name);
                        ConsoleHelper.WriteSuccessLine($"Table [{t.Name}] Created Successfully");
                        dbContext.Db.CodeFirst.InitTables(t);
                        //dbContext.DbClient.QueryableByObject(t).ToList() == null
                        string seedData = FileHelper.ReadFile(string.Format(SeedDataFolder, t.Name), Encoding.UTF8);
                        #region Sys_User
                        #region AddSeedData
                        if (seedData != "不存在相应的目录")
                        {
                            List<Dictionary<string, object>> dic = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(seedData);
                            //dbContext.GetEntityDB<BlogArticle>().InsertRange(JsonHelper.ParseFormByJson<List<BlogArticle>>());
                            //Console.WriteLine("Table:BlogArticle created success!");
                            List<Dictionary<string, object>> dicFile = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(seedData);
                            for (int i = 0; i < dic.Count; i++)
                            if (dicFile.Count > 0)
                            {
                                if (dic[i].ContainsKey("CreateDate"))
                                    dic[i]["CreateDate"] = DateTime.Now;
                                else
                                    dic[i].Add("CreateDate", DateTime.Now);
                            }
                                List<Dictionary<string, object>> dic = new List<Dictionary<string, object>>();
                            dbContext.Db.Insertable(dic).AS(t.Name).ExecuteCommand();
                                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];
                                        SequenceAttribute? sequenceAttirbute = propertyInfo.GetCustomAttribute<SequenceAttribute>();
                                        if (sequenceAttirbute != null)
                                        {
                                            int count = dbContext.Db.Ado.GetScalar($"SELECT COUNT(*) FROM sys.sequences WHERE name = '{sequenceAttirbute.SequenceName}'").ObjToInt();
                                            if (count == 0)
                                            {
                                                string sql = $"CREATE SEQUENCE {sequenceAttirbute.SequenceName} AS [int] START WITH {sequenceAttirbute.StartWith} INCREMENT BY {sequenceAttirbute.Increment} MINVALUE {sequenceAttirbute.SeqMinValue} MAXVALUE {sequenceAttirbute.SeqMaxValue} {(sequenceAttirbute.IsCycle ? "CYCLE" : "")} CACHE";
                                                dbContext.Db.Ado.ExecuteCommand(sql);
                                            }
                                        }
                                        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 = "";
                                    if (DBContext.DbType == SqlSugar.DbType.SqlServer)
                                    {
                                        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);
                                    }
                                    else
                                    {
                                        dbContext.Db.Insertable(dic).AS(t.Name).ExecuteCommand();
                                    }
                                    ConsoleHelper.WriteSuccessLine($"Table [{t.Name}] SeedData Added Successfully");
                                }
                            }
                        }
                        #endregion
                    }
@@ -115,7 +173,18 @@
                            for (int i = 0; i < propertyInfos.Count; i++)
                            {
                                PropertyInfo propertyInfo = propertyInfos[i];
                                SugarColumn sugarColumn = propertyInfo.GetCustomAttribute<SugarColumn>();
                                SequenceAttribute? sequenceAttirbute = propertyInfo.GetCustomAttribute<SequenceAttribute>();
                                if (sequenceAttirbute != null)
                                {
                                    int count = dbContext.Db.Ado.GetScalar($"SELECT COUNT(*) FROM sys.sequences WHERE name = '{sequenceAttirbute.SequenceName}'").ObjToInt();
                                    if (count == 0)
                                    {
                                        string sql = $"CREATE SEQUENCE {sequenceAttirbute.SequenceName} AS [int] START WITH {sequenceAttirbute.StartWith} INCREMENT BY {sequenceAttirbute.Increment} MINVALUE {sequenceAttirbute.SeqMinValue} MAXVALUE {sequenceAttirbute.SeqMaxValue} {(sequenceAttirbute.IsCycle ? "CYCLE" : "")} CACHE";
                                        dbContext.Db.Ado.ExecuteCommand(sql);
                                    }
                                }
                                SugarColumn? sugarColumn = propertyInfo.GetCustomAttribute<SugarColumn>();
                                if (sugarColumn != null)
                                {
                                    if (!sugarColumn.IsIgnore)
@@ -133,7 +202,7 @@
                        }
                    }
                });
                ConsoleHelper.WriteSuccessLine($"Tables created successfully!");
                ConsoleHelper.WriteSuccessLine($"Tables Created Successfully!");
                Console.WriteLine();