首页 > 数据库 >sqlsugar 封装 单例模式 多数据库 泛型

sqlsugar 封装 单例模式 多数据库 泛型

时间:2024-08-30 20:52:18浏览次数:11  
标签:string connectStr dbInfo PlayGround 单例 泛型 new public sqlsugar

PlayGround\.config\dotnet-tools.json


{
  "version": 1,
  "isRoot": true,
  "tools": {
    "csharpier": {
      "version": "0.29.1",
      "commands": [
        "dotnet-csharpier"
      ],
      "rollForward": false
    }
  }
}

PlayGround\.vscode\launch.json


{
    "version": "0.2.0",
    "configurations": [
        {
            // Use IntelliSense to find out which attributes exist for C# debugging
            // Use hover for the description of the existing attributes
            // For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceFolder}/bin/Debug/net9.0/PlayGround.dll",
            "args": [],
            "cwd": "${workspaceFolder}",
            // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
            "console": "internalConsole",
            "stopAtEntry": false
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach"
        }
    ]
}

PlayGround\.vscode\tasks.json


{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/Playground.sln",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary;ForceNoAlign"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "publish",
            "command": "dotnet",
            "type": "process",
            "args": [
                "publish",
                "${workspaceFolder}/Playground.sln",
                "/property:GenerateFullPaths=true",
                "/consoleloggerparameters:NoSummary;ForceNoAlign"
            ],
            "problemMatcher": "$msCompile"
        },
        {
            "label": "watch",
            "command": "dotnet",
            "type": "process",
            "args": [
                "watch",
                "run",
                "--project",
                "${workspaceFolder}/Playground.sln"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}

PlayGround\.csharpierrc

PlayGround\appsettings.json


{
  "ConnectionStrings": {
    "AppOne": "Server=localhost;Database=DDD;Trusted_Connection=True;MultipleActiveResultSets=true",
    "MySqlConnection": "Server=localhost;Database=ElectricDDD;Uid=root;Pwd=123456;"
  },
  "DataProvider": "MsSql",
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "Authentication": {
    "JwtBearer": {
      "SecurityKey": "ELETRICAPIC421AAEE0D114E9C",
      "Issuer": "EletricAPI",
      "Audience": "EletricAPI"
    }
  },
  "CorsOrigins": "http://localhost:9527",
  "AllowedHosts": "*"
}

PlayGround\Entity.cs


public class SugarEntity
{
    public SugarEntity()
    {
    }
}

PlayGround\PlayGround.csproj


<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
  <ItemGroup>
  <PackageReference Include="DataTablePrettyPrinter" Version="0.2.0" />
  <PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    <PackageReference Include="SqlSugarCore" Version="5.1.4.168-preview11" />
    <PackageReference Include="System.Data.SqlClient" Version="4.8.6" />
  </ItemGroup>

  <ItemGroup>
    <None Update="appsettings.json">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </None>
    <None Update="nlog.config" CopyToOutputDirectory="Always" />
  </ItemGroup>

</Project>

PlayGround\Playground.sln

PlayGround\Program.cs


using System.Data;
using DataTablePrettyPrinter;
using Microsoft.Extensions.Configuration;
using SqlSugarFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
        IConfigurationRoot configurationRoot = configurationBuilder.SetBasePath(AppContext.BaseDirectory).AddJsonFile("appsettings.json", optional: true, reloadOnChange: true).Build();
        IConfigurationSection dbConfigurationSection = configurationRoot.GetSection("ConnectionStrings");
        LongSugarClient longSugarClient = LongSugarClient.GetInstance(DbInfo.MesOne, dbConfigurationSection);

        DataTable dataTable = longSugarClient.ExcuteRawSql("SELECT * FROM [DDD].[dbo].[EleTodo]");
        Console.WriteLine(dataTable.ToPrettyPrintedString());
        foreach (DataRow dataRowrow in dataTable.Rows)
        {
            System.Console.WriteLine(dataRowrow[0]);
        }
    }
}


PlayGround\run.bat


dotnet run

PlayGround\SqlSugarCore.cs


using System.Data;
using System.Linq.Expressions;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace SqlSugarFrameworkCore;

public class DbSettings
{
    public const string MesOne = "AppOne";
    public const string MesDevOne = "AppDevOne";
    public const string MesThreeOne = "AppThreeOne";
    public const string Oracle = "Oracle";
}

public enum DbInfo
{
    MesOne = 1,
    MesDevOne = 2,
    MesThree = 3,
    Oracle = 4,
}


public class LongSugarClient
{
    public static LongSugarClient sugarInstance;
    public static DbInfo curDbInfo;
    public static Dictionary<DbInfo, LongSugarClient> sugarInstances = new Dictionary<DbInfo, LongSugarClient>();

    public static readonly object sugarInstanceLock = new object();
    public SqlSugarClient _db;

    private LongSugarClient(SqlSugarClient sqlSugarClient)
    {
        _db = sqlSugarClient;
    }

    public static LongSugarClient GetInstance(DbInfo dbInfo, IConfigurationSection dbConfigurationSection)
    {
        if (sugarInstances.ContainsKey(dbInfo))
        {
            sugarInstances.TryGetValue(dbInfo, out LongSugarClient sugarInstance);
            return sugarInstance;
        }

        lock (sugarInstanceLock)
        {
            if (sugarInstances.ContainsKey(dbInfo))
            {
                sugarInstances.TryGetValue(dbInfo, out LongSugarClient sugarInstance);
                return sugarInstance;
            }
            GetSugarClient(dbInfo, dbConfigurationSection);
        }
        return sugarInstance;
    }

    private static void GetSugarClient(DbInfo dbInfo, IConfigurationSection dbConfigurationSection)
    {
        if (dbInfo == DbInfo.MesOne)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.MesOne).Value ?? throw new ArgumentNullException($"{DbSettings.MesOne} is misstion");

            System.Console.WriteLine(connectStr);
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.MesDevOne)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.MesDevOne).Value ?? throw new ArgumentNullException($"{DbSettings.MesDevOne} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.MesThree)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.MesThreeOne).Value ?? throw new ArgumentNullException($"{DbSettings.MesThreeOne} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
        else if (dbInfo == DbInfo.Oracle)
        {
            string connectStr = dbConfigurationSection.GetSection(DbSettings.Oracle).Value ?? throw new ArgumentNullException($"{DbSettings.Oracle} is misstion");
            CreateSugarClient(dbInfo, connectStr);
        }
    }

    private static void CreateSugarClient(DbInfo dbInfo, string connectStr)
    {
        SqlSugarClient sqlSugar = new SqlSugarClient(
            new ConnectionConfig()
            {
                DbType = SqlSugar.DbType.SqlServer,
                ConnectionString = connectStr,
                IsAutoCloseConnection = true,
            },
            db =>
            {
                //单例参数配置,所有上下文生效
                db.Aop.OnLogExecuting = (sql, pars) =>
                {
                    //打印日志
                    // Console.WriteLine(sql + "\r\n" + db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                };
            }
        );
        sugarInstance = new LongSugarClient(sqlSugar);
        sugarInstances.Add(dbInfo, sugarInstance);
    }


    public DataTable ExcuteRawSql(string sql)
    {
        DataTable dataTable = this._db.SqlQueryable<DataTable>(sql).ToDataTable();
        return dataTable;
    }

    public List<T> ExcuteRawSql<T>(string sql)
        where T : SugarEntity, new()
    {
        List<T> list = this._db.SqlQueryable<T>(sql).ToList();
        return list;
    }

}

PlayGround\TodoEntity.cs


public enum TodoStatus
{
    Undo,
    Done,
}

public class EleTodo : SugarEntity
{
    public EleTodo()
    {
    }

    public Guid Id { get; set; }

    public string Name { get; set; }

    public TodoStatus Status { get; set; }

    public string? Remark { get; set; }

    public Guid UserId { get; set; }
}

public class EleTodoCount : SugarEntity
{
    public int Count { get; set; }
}
 

PlayGround\zz.bat


set "scriptPath=%cd%" 
D: && cd D:\dotnet.-script\App\bin\Debug\net8.0\ && D:\dotnet.-script\App\bin\Debug\net8.0\App.exe  "%scriptPath%"   "Question"


  












标签:string,connectStr,dbInfo,PlayGround,单例,泛型,new,public,sqlsugar
From: https://www.cnblogs.com/zhuoss/p/18389488

相关文章

  • 【ES6】使用Proxy实现单例模式
    前言由于JS没有private关键字,无法私有化构造器,所以下面代码无法限制:classPerson{constructor(){console.log("Personcreated");}}constp1=newPerson();constp2=newPerson();console.log(p1===p2);//false实现通过Person.getInstanc......
  • day03-面向对象-内部类&泛型&常用API
    一、内部类内部类是类中的五大成分之一(成员变量、方法、构造器、代码块、内部类)如果一个类定义在另一个类的内部,这个类就是内部类。场景:当一个类的内部,包含了一个完整的事物,且这个事物没有必要单独设计时,就可以把这个事物设计成内部类内部类分为四种:成员内部类[了解]......
  • sqlsugar 封装 单例模式 多数据库
    #PlayGround\.config\dotnet-tools.json{"version":1,"isRoot":true,"tools":{"csharpier":{"version":"0.29.1","commands":["dotnet-csharpi......
  • sqlsugar 单例模式 封装
    usingSystem.Linq.Expressions;usingMicrosoft.Extensions.Configuration;usingSqlSugar;namespaceSqlSugarFrameworkCore;publicclassDbSettings{publicconststringAppOne="AppOne";publicconststringAppDevOne="AppDevOne";pub......
  • 【设计模式】单例模式(线程安全)
     ......
  • 单例模式 lock 多线程 双重检查锁定机制
    单例模式单例模式publicclassSingleton{//定义一个静态变量来保存类的实例privatestaticSingletonuniqueInstance;//定义一个标识确保线程同步privatestaticreadonlyobjectlocker=newobject();//定义私有构造函数,使外界不能创建该类......
  • 单例模式
    1.单线程单例确保一个类只有一个实例,并提供一个访问它的全局访问点概念拆分(1.一个类只有一个实例2.提供一个全局访问点)publicclassSingleton{privatestaticSingletonsingleton;//定义一个静态变量来保护类的实例publicstaticSingleton......
  • JS单例模式; super return 改变this
    简单的单例首先js中的函数是一种特殊的对象,这使得他可以存储属性functionaaa(params){}//undefinedaaa.lalala=123//123js中的类是通过原型链继承的,因此类就是函数的集合体,可以通过babel编译看看。因此可以写出简单的单例模式classSingleton{constructor(da......
  • Java--泛型
    目录什么是泛型泛型的作用泛型的特性泛型的使用泛型类泛型接口泛型方法泛型通配符什么是泛型泛型是JavaSE5中引入的一个新特性,它提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型。简单来说,泛型是一种参数化类型,它可以将类型(类、接口、枚举等)作为参数传......
  • Java泛型
    Java泛型是Java语言的一个重要特性,它允许你在编译时指定类型参数,从而编写更加灵活和可重用的代码。Java泛型的概念Java泛型是在JDK5.0中引入的,它允许你在声明类、接口和方法时使用类型参数。类型参数可以是你定义的任何标识符,通常使用大写字母如E,T,K,V等表示。使用泛型......