SqlSugar ORM Documentation

repository·master·Indexed 27 days ago

https://github.com/dotnetnext/sqlsugar

A high-performance, open-source ORM for .NET supporting .NET Framework and .NET Core 3.1 through .NET 10. It provides features for multi-tenancy, automatic table splitting, and big data bulk operations via the .Fastest<T>() API. Compatible with a wide range of databases including MySql, SqlServer, Sqlite, Oracle, Postgresql, Mongodb, and others. Includes capabilities for dynamic expressions, global query filters, and complex join queries.

Tokens
3.3K
Snippets
10
Records
17
Agent score
41%

What's inside SqlSugar

  1. Overview of SqlSugar ORM

    master
    SqlSugar is an open-source .NET ORM framework designed for ease of use, high performance, and comprehensive features. It supports zero-SQL table building, CRUD operations, and is suitable for big data scenarios (millions of writes/updates and billions of queries). It is highly compatible with multiple databases and supports SAAS application requirements like multi-tenancy and cross-database queries.
  2. Configure the SqlSugar Performance Benchmark Suite

    master

    Before running the benchmark suite, you must configure your database connection. Open BenchmarkConfig.cs and update the SqlServerConnection constant with your valid SQL Server connection string.

    Requirements:

    • .NET 6.0 or higher
    • SQL Server (default)
    • BenchmarkDotNet 0.13.12+
    public const string SqlServerConnection = "server=.;uid=sa;pwd=YOUR_PASSWORD;database=SqlSugarBenchmark;Encrypt=True;TrustServerCertificate=True";
  3. Run validation tests for the benchmark suite

    master

    Before executing full benchmarks, run validation tests to ensure your database connection, entity creation, CRUD operations, bulk operations, join queries, and navigation properties are working correctly.

    You can use the provided PowerShell script (recommended) or the dotnet CLI.

    # Using PowerShell script (Recommended)
    .\RunTests.ps1
    
    # Or using dotnet CLI
    dotnet run -c Release -- --test
  4. Manage Multi-tenant Transactions

    master

    SqlSugar supports transactions across multiple database connections. You can define multiple ConnectionConfig objects in a SqlSugarClient and use BeginTran() and CommitTran() to ensure atomicity across different databases.

    // Create database object with multiple connections
    SqlSugarClient db = new SqlSugarClient(new List<ConnectionConfig>()
    {
        new ConnectionConfig(){ ConfigId="0", DbType=DbType.SqlServer,  ConnectionString=Config.ConnectionString, IsAutoCloseConnection=true },
        new ConnectionConfig(){ ConfigId="1", DbType=DbType.MySql, ConnectionString=Config.ConnectionString4 ,IsAutoCloseConnection=true}
    });
    
    var mysqldb = db.GetConnection("1"); // mysql db
    var sqlServerdb = db.GetConnection("0"); // sqlserver db
     
    db.BeginTran();
                mysqldb.Insertable(new Order()
                {
                    CreateTime = DateTime.Now,
                    CustomId = 1,
                    Name = "a",
                    Price = 1
                }).ExecuteCommand();
                mysqldb.Queryable<Order>().ToList();
                sqlServerdb.Queryable<Order>().ToList();
    
    db.CommitTran();
  5. Apply Global Query Filters

    master
    You can set global filters using db.QueryFilter.Add(). This automatically applies the specified condition to all subsequent queries on that table, which is useful for soft-deletes or multi-tenant data isolation.
  6. Implement Singleton Pattern for Transactions

    master

    Use SqlSugarScope to implement a singleton pattern that allows you to manage transactions across different methods. You can wrap multiple service calls within a Db.UseTran() block to ensure they all participate in the same transaction.

    public static SqlSugarScope Db = new SqlSugarScope(new ConnectionConfig()
     {
                DbType = SqlSugar.DbType.SqlServer,
                ConnectionString = Config.ConnectionString,
                IsAutoCloseConnection = true 
      },
      db=> {
                db.Aop.OnLogExecuting = (s, p) =>
                {
                    Console.WriteLine(s);
                };
     });
     
     using (var tran = Db.UseTran())
     {
              
                   new Test2().Insert(XX);
                   new Test1().Insert(XX);
                   ..... 
                    ....
                             
                 tran.CommitTran(); 
     }
  7. Perform Insert or Update (Upsert)

    master

    The .Storageable() method provides a convenient way to perform 'Insert or Update' operations. It can handle lists of entities and supports setting page sizes for large datasets.

    Db.Storageable(list2).ExecuteCommand();
    Db.Storageable(list2).PageSize(1000).ExecuteCommand();
    Db.Storageable(list2).PageSize(1000,exrows=> {   }).ExecuteCommand();
  8. Perform Join Queries

    master

    Use the .LeftJoin<T> method to perform simple join queries with a fluent syntax. You can chain multiple joins and use .Select to map the results to a specific DTO or view model.

    var query  = db.Queryable<Order>()
                .LeftJoin<Custom>  ((o, cus) => o.CustomId == cus.Id)
                .LeftJoin<OrderItem> ((o, cus, oritem ) => o.Id == oritem.OrderId)
                .LeftJoin<OrderItem> ((o, cus, oritem , oritem2) => o.Id == oritem2.OrderId)
                .Where(o => o.Id == 1)  
                .Select((o, cus) => new ViewOrder { Id = o.Id, CustomName = cus.Name })
                .ToList();   
  9. Configure Auto Split Tables

    master

    SqlSugar supports automatic table splitting (e.g., by year, month, etc.) using attributes. Use [SplitTable] to define the split type and [SugarTable] to define the naming pattern. A [SplitField] must be designated to tell SqlSugar which field to use for determining the correct sub-table during CRUD operations.

    [SplitTable(SplitType.Year)] // Supports year, quarter, month, week and day
    [SugarTable("SplitTestTable_{year}{month}{day}")] 
     public class SplitTestTable
     {
         [SugarColumn(IsPrimaryKey =true)]
         public long Id { get; set; }
     
         public string Name { get; set; }
         
         [SplitField] 
         public DateTime CreateTime { get; set; } 
     }
    
    // Querying split tables
     var lis2t = db.Queryable<OrderSpliteTest>()
    .SplitTable(DateTime.Now.Date.AddYears(-1), DateTime.Now)
    .ToPageList(1,2);
  10. Perform Big Data Bulk Operations

    master

    For high-performance data operations, use the .Fastest<T>() API. This provides specialized methods for bulk processing:

    • BulkCopy: High-speed insertion of entities or DataTables.
    • BulkUpdate: High-speed updates. You can specify the primary key or a custom set of columns to update.
    • BulkMerge: High-speed upsert (insert or update).
    • BulkDelete: High-speed deletion using .Deleteable<T>(list).PageSize(n).ExecuteCommand().
    • BulkQuery: For large data exports, use .ForEach() with a batch size to avoid memory issues.