SqlSugar ORM Documentation
repository·master·Indexed 27 days ago
https://github.com/dotnetnext/sqlsugarA 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.
What's inside SqlSugar
- 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.
Configure the SqlSugar Performance Benchmark Suite
masterBefore running the benchmark suite, you must configure your database connection. Open
BenchmarkConfig.csand update theSqlServerConnectionconstant 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";Run full or specific SqlSugar benchmarks
masterTo execute the complete performance benchmark suite, use
dotnet runwith theReleaseconfiguration. To save time, you can run specific benchmark categories using the--filterflag.Run all benchmarks:
dotnet run -c ReleaseRun specific benchmarks (e.g., QueryBenchmarks):
dotnet run -c Release -- --filter *QueryBenchmarks*Run validation tests for the benchmark suite
masterBefore 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 -- --testTroubleshoot database connection errors in benchmarks
masterIf you encounter the error
A network-related or instance-specific error occurred, follow these steps:- Verify the connection string in
BenchmarkConfig.cs. - Ensure SQL Server is currently running.
- Check your firewall settings.
- Confirm the database user has the necessary permissions.
- Verify the connection string in
Manage Multi-tenant Transactions
masterSqlSugar supports transactions across multiple database connections. You can define multiple
ConnectionConfigobjects in aSqlSugarClientand useBeginTran()andCommitTran()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();Apply Global Query Filters
masterYou can set global filters usingdb.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.Implement Singleton Pattern for Transactions
masterUse
SqlSugarScopeto implement a singleton pattern that allows you to manage transactions across different methods. You can wrap multiple service calls within aDb.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(); }Perform Insert or Update (Upsert)
masterThe
.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();Perform Join Queries
masterUse the
.LeftJoin<T>method to perform simple join queries with a fluent syntax. You can chain multiple joins and use.Selectto 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();Configure Auto Split Tables
masterSqlSugar 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);Perform Big Data Bulk Operations
masterFor 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.