流浪のwolf

卷帝

导航

sqlSugar 使用原生模式链接数据库

using System.Reflection;
using zhulongxu_webapi_pro.Tools;

namespace zhulongxu_webapi_pro.Services
{
    /// <summary>
    /// 初始化数据库
    /// </summary>
    public static class InitDataBaseService
    {
        public static void InitDataBase(this WebApplicationBuilder builder)
        {
            var conneString = settingsTool.Get("ConnectionString", true);
            ConnectionConfig connection = new ConnectionConfig()
            {
                ConnectionString = conneString,  // 数据库链接字符串
                DbType = DbType.PostgreSQL,  // 什么数据库
                IsAutoCloseConnection = true,  // 是否自动关闭链接
            };
            using (SqlSugarClient client = new SqlSugarClient(connection))
            {
                // 读取配置文件
                // 如果有数据库就执行删除操作 没有就不会操作
                client.DbMaintenance.CreateDatabase();
                //if (client.DbMaintenance.IsAnyTable("pagingdata`1", false))
                //{
                //    client.DbMaintenance.DropTable("pagingdata`1");  // 删除 userinfo 表格
                //}
                // 找到运行文件的映射 assembly  通过反射读取 dll 文件
                // 反射  1. 获取实体文件的反射  2. 获取对应命名空间
                Assembly assembly = Assembly.LoadFile(Path.Combine(AppContext.BaseDirectory, "zhtestxu.Domain.dll"));

                // zhulongxu.Domain.Entries 这个命名空间的所有类都会被映射成表
                // ps: t.Name 表示类名  t.NameSpace 表示命名空间
                Type[] typeArray = assembly.GetTypes().ToArray();
                // 生成表
                client.CodeFirst.InitTables(typeArray);
            }
        }
    }
}

 

posted on 2024-05-31 18:41  流浪のwolf  阅读(10)  评论(0编辑  收藏  举报