Skip to content

Fast.SqlSugar ​

Public members, parameters, returns, and exceptions

Reference source version 3.5.76; targets: net8.0;net9.0;net10.0.

When upgrading code that uses platform flags, see the Runtime H5 migration guide and the dependency history.

The centrally managed SqlSugarCore version is 5.1.4.221. Version 3.5.69 adjusts entity assignment checks and callback timing while retaining the existing empty-value fill rules. The paging output field removal from 3.5.68 and department entity interface extraction from 3.5.67 remain in effect.

Contract and constraints ​

Scoped repositories, entity auditing, connection selection and paging. AddSqlSugar() defaults to ConnectionSettings. Register or discover an ISqlSugarEntityHandler implementation; the client factory requires it. Its constructor must not depend on ISqlSugarClient and create a cycle. The static connection options read by the factory are not automatically post-configured: supply complete configuration or call PostConfigure explicitly in the callback before overriding values. Repository queries return counts, existence, entities or lists; missing single results require null handling even where annotations are absent. Writes, logical deletes and schema utilities perform real database operations. Calls are not automatically grouped into a transaction. PagedInput defaults to PageIndex=1, PageSize=20 and EnablePaged=true; MaxNotPageSize defaults to 10000. Assign unique Snowflake worker IDs per instance. The examples below query existing tables without creating a schema or writing data.

Connection and public API migration in 3.5.73 ​

The source remains at 3.5.73; this update does not increment the version again. These changes include breaking contracts. The patch version does not imply source, binary or numeric-value compatibility; update consumers and rebuild them.

Previous contractCurrent contract and migration
DbConnectionInfoRemoved. Use ConnectionSettingsOptions for primary configuration and SlaveConnectionInfo for replicas. Consumer database record models must declare their own fields and mappings
ConnectionSettingsOptions : DbConnectionInfoDirectly implements IPostConfigure and declares its connection fields. Update base-type references, derived implementations and overrides that depended on virtual members
SlaveConnectionInfo : DbConnectionInfoIndependent type without PostConfigure() or CustomConnectionStr; it does not inherit primary defaults. HitRate is no longer virtual
Configuration inheritance and mappingsFormer virtual members such as SlaveConnectionList are no longer virtual, and the configuration fields no longer carry their previous SugarColumn attributes. Do not use these options as an unchanged persistence model
SqlSugarDatabaseUtilInternal implementation. Use the public SqlSugarContext.GetConnectionConfig(options) for connection configuration; replace other helper calls with supported SqlSugar APIs or consumer-owned code
repository.EntitiesReplace with inherited repository.Queryable<TEntity>(). Count/Any/Single/First/ToList convenience queries also use this entry point internally

SugarDbType values and conversions ​

SugarDbType now retains only the six members below. Migrate persisted numbers, numeric request values, configuration and generated client enums by their previous meanings. Do not add one to every value; the default value 0 no longer means MySql.

MemberPrevious valueCurrent value
MySql01
SqlServer12
Sqlite23
Oracle34
PostgreSQL45
MongoDb326

Other former members, including Dm, MySqlConnector, Access and Custom, are removed. ToDbType() and ToSugarDbType() accept only these six types; undefined values and other database types throw ArgumentOutOfRangeException. SqlSugar.DbType.MySqlConnector.ToSugarDbType() is also unsupported.

ConnectionSettingsOptions.DbType remains the separate SqlSugar.DbType? type, whose values are unchanged. Use the public conversion methods between these enums instead of numeric casts. Do not apply this migration table to connection settings that use SqlSugar.DbType.

Entity assignment in 3.5.69 ​

For each field callback in InsertByObject and UpdateByObject, the property name is matched before its value is read and the fill condition is checked. The new value is evaluated and assigned only after these checks pass. AssignDepartmentId/Name, AssignUserId/Name and AssignTenantId no longer run eagerly for unrelated properties; insert callbacks also skip the corresponding handlers for already populated fields. If reading a property fails, its automatic assignment is skipped.

On insertion, a null/zero RowVersion is still initialized to 1. Department, tenant and creator IDs are still filled only when null/zero, and department and creator names only when null/empty. Fields supplied by a handler still require a handler to be present.

On insertion, CreatedTime is still set to DateTime.Now only when its current value is null; caller-supplied creation timestamps are retained. On update, a readable UpdatedTime is still replaced with the current time; updater IDs/names are still replaced with handler values when a handler is present, and the handler is called only for the matching field. Public API declarations and dependency versions are unchanged.

Paging output field migration in 3.5.68 ​

PagedOutput no longer provides DepartmentName; the remaining audit fields and RowVersion retain their contracts. Paging DTOs without department information can keep inheriting it directly. DTOs that still return a department name must declare the property and populate it through their query projection or assignment:

csharp
#nullable enable

using Fast.SqlSugar;

/// <summary>
/// Paging output with a department name
/// </summary>
public sealed class DepartmentPagedOutput : PagedOutput
{
    /// <summary>
    /// Department name
    /// </summary>
    public string? DepartmentName { get; set; }
}

Update existing override declarations, base.DepartmentName access and generic member access constrained only to PagedOutput, then recompile dependent assemblies. Default serialization of the base type no longer includes the department name. When preserving the response field, also review the declared return type, JSON naming policy and client model. Paging DTOs do not need to implement IDepartmentEntity for this purpose; that entity interface and the department assignment hooks retain their contracts.

Department field migration in 3.5.67 ​

BaseEntity/IBaseEntity and BaseRecordEntity/IBaseRecordEntity no longer declare DepartmentId or DepartmentName. BaseTEntity, which inherits BaseEntity, no longer supplies them either. This is a breaking public API change. Entities without department information do not need replacement properties.

Entities requiring department ownership or a department audit snapshot should explicitly implement IDepartmentEntity and declare both properties and their SqlSugar mappings. The interface supplies neither property implementations nor SugarColumn configuration. This example preserves the previous types, length, nullability and column ordering:

csharp
using Fast.SqlSugar;
using SqlSugar;

[SugarTable("DepartmentDocument")]
public sealed class DepartmentDocument : BaseTEntity, IDepartmentEntity
{
    [SugarColumn(IsPrimaryKey = true)]
    public long Id { get; set; }

    [SugarColumn(ColumnDescription = "部门Id", CreateTableFieldSort = 989)]
    public long? DepartmentId { get; set; }

    [SugarColumn(ColumnDescription = "部门名称", Length = 20, IsNullable = true, CreateTableFieldSort = 990)]
    public string DepartmentName { get; set; } = "";
}

Generic constraints, expressions and mappings that access department properties through IBaseEntity or IBaseRecordEntity must instead use IDepartmentEntity or the concrete entity. Consumers that also access audit properties must retain the applicable audit contract. BaseRecordEntity now orders device, OS, browser, province, city and IP columns at 971–976; creator and creation-time contracts remain unchanged.

On object insertion, SugarEntityFilter still matches department property names without checking whether the entity implements IDepartmentEntity. With a handler present, it fills null/zero department IDs and null/empty department names from the handler while retaining existing nonempty values. Object updates do not automatically reassign a department. Implementing the interface does not enable department authorization filters; existing global filters still cover tenancy and soft deletion.

Before migration, review whether the department represents data ownership or a creation-time snapshot, and inspect application data-permission conditions. Removing source properties does not drop existing database columns. Review existing columns, historical data, indexes and constraints separately; documentation validation must not initialize, migrate or alter a database.

Connection defaults, pools and replicas ​

The table describes ConnectionSettingsOptions.PostConfigure(). The static options consumed by the factory are not automatically post-configured. Explicitly call PostConfigure() before overrides or supply complete settings.

OptionPostConfigure default / constraint
DbTypeSqlServer
ServiceIp, Port, DbUser127.0.0.1, 1433, sa; port selection is not database-aware
MaxPoolSize100; generated MySql/MySqlConnector, SqlServer and PostgreSQL primary/replica strings use the respective setting
CommandTimeOut60 seconds
SugarSqlExecMaxSeconds30 seconds
DiffLog, DisableAopfalse, true
ConnectionId, DbName, DbPwd, CustomConnectionStrNo defaults

The placeholders below must be replaced by the consumer. This snippet only builds options and does not connect to a database. After switching to MySql, explicitly set port 3306 because PostConfigure() defaults to 1433.

csharp
using Fast.SqlSugar;
using DbType = SqlSugar.DbType;

var options = new ConnectionSettingsOptions();
options.PostConfigure();
options.ConnectionId = "main";
options.DbType = DbType.MySql;
options.ServiceIp = "DB_HOST";
options.Port = 3306;
options.DbName = "DB_NAME";
options.DbUser = "DB_USER";
options.DbPwd = "DB_PASSWORD";
options.MaxPoolSize = 200;
options.SlaveConnectionList =
[
    new SlaveConnectionInfo
    {
        ServiceIp = "REPLICA_HOST",
        Port = 3306,
        DbName = "DB_NAME",
        DbUser = "DB_USER",
        DbPwd = "DB_PASSWORD",
        MaxPoolSize = 50,
        HitRate = 1
    }
];

Replica fields are independent and do not inherit the primary address, credentials or defaults. If a replica port is null, the connection-string generator uses the port for its database type. HitRate is a selection weight; 0 disables selection. SlaveConnectionInfo.CommandTimeOut is not currently applied as an independent replica command timeout.

Generated MySql, MySqlConnector, SqlServer and PostgreSQL primary/replica strings use their respective MaxPoolSize, with a fallback of 100. A nonblank CustomConnectionStr is used directly and suppresses the entire SlaveConnectionList. Host, port, database, credential and pool fields no longer construct the primary string; configure pooling inside the custom string.

The ISqlSugarClient factory falls back to 30/false/true when SugarSqlExecMaxSeconds/DiffLog/DisableAop are null. These local fallbacks do not fill all static options. DbType, CommandTimeOut and the generic repository constructor still require complete settings.

Installation and examples ​

Install the package ​

bash
dotnet add package Fast.SqlSugar

Example 1 ​

csharp
using Fast.SqlSugar;

public static class PagingDefaults
{
    public static PagedInput FirstPage() => new() { PageIndex = 1, PageSize = 20 };
}

Example 2 ​

csharp
using Fast.SqlSugar;
using SqlSugar;

[SugarTable("CatalogItem")]
public sealed class CatalogItem
{
    [SugarColumn(IsPrimaryKey = true)]
    public long Id { get; set; }
    public string Name { get; set; } = "";
}

public sealed class CatalogReader(ISqlSugarRepository<CatalogItem> repository)
{
    public ISugarQueryable<CatalogItem> QueryByName(string name) =>
        repository.Queryable<CatalogItem>().Where(item => item.Name == name);

    public Task<int> CountAsync(string name) =>
        repository.CountAsync(item => item.Name == name);

    public Task<bool> ExistsAsync(long id) =>
        repository.AnyAsync(item => item.Id == id);

    public Task<CatalogItem> FindAsync(long id) =>
        repository.SingleOrDefaultAsync((object)id);
}

Web-host examples belong in a consumer project using Microsoft.NET.Sdk.Web and a supported .NET target. IaaS examples can be used in an ordinary class library. Registration precedes builder.Build(); configure middleware and endpoints before app.Run(). Samples retain their original code and comments. On 2026-10-17, the current working-tree entity assignment changes for 3.5.69 were reviewed. After restoring null-only CreatedTime filling, Release builds and local packaging passed for net8.0, net9.0 and net10.0. Package identity, assembly versions, DLL/XML assets and equality of packaged DLLs with the latest build outputs were verified. At that time, dependencies and all 278 public/protected declarations in each bilingual API reference were unchanged; that historical record does not cover the current 3.5.73 API migration. Handler timing and empty-value rules were reviewed from source; no runtime regression or live entity-save workflow was run. That historical build reported transitive System.Security.Cryptography.Pkcs 8.0.1 NU1902/NU1903 warnings; the 3.5.72 dependency changes below have not been verified by a new restore. No business host, database connection, data operation or schema operation was run.

Source reference ​

Non-paged limits ​

Non-paged queries fetch at most MaxNotPageSize + 1 rows to distinguish exactly N from more than N. Exactly N is allowed; N+1 is rejected in both sync and async paths. The configured limit must be 1 through int.MaxValue-1. Paging safeguards remain in place.

Dependency alignment on 2026-11-02 ​

2026-11-02 dependency alignment: this package increments from 3.5.75 to 3.5.76, updating its dependency to Fast.Runtime 3.5.37. This module's implementation and public declarations are unchanged. Runtime adds mobile H5 and shifts Android and subsequent flags; migrate numeric protocols/masks, rebuild consumers and regenerate client enums. See the Runtime H5 migration guide.

2026-10-24 versions and dependencies ​

On 2026-10-24, this package increments from 3.5.71 to 3.5.72, with dependencies updated to Fast.Runtime 3.5.34. This module's own implementation and public declarations are unchanged.

Explicitly reference System.Security.Cryptography.Pkcs, centrally pinned to 8.0.2, 9.0.21 and 10.0.13 for net8.0, net9.0 and net10.0 respectively. Remove the explicit SQLitePCLRaw.bundle_e_sqlite3 reference and central 3.0.5 override; SQLite dependencies are resolved transitively through the unchanged SqlSugarCore 5.1.4.221. No restore was run, so the resolved SQLite version and removal of earlier vulnerability warnings have not been verified.

Consumers using AppEnvironmentEnum must migrate numeric values and rebuild according to the Runtime HarmonyOS migration guide. This batch reviewed source and effective MSBuild package metadata only. Tests were skipped as requested; no restore, build, pack or consumer runtime validation was performed.

2026-10-30 dependency patch updates ​

Fast.SqlSugar increments from 3.5.72 to 3.5.73. For net8.0 / net9.0 / net10.0, System.Security.Cryptography.Pkcs uses 8.0.2 / 9.0.22 / 10.0.14. The net8.0 dependency remains at 8.0.2; only the net9.0 and net10.0 dependency patches change. Fast.Runtime 3.5.34 and SqlSugarCore 5.1.4.221 are unchanged.

This dependency update does not modify module implementation or public APIs. Restore, Release builds and local packaging passed for all three targets without final build warnings or errors. Package identity, dependency groups and DLL/XML equality with build outputs were verified. No host, HTTP/serialization/ORM runtime regression, database or Redis operation was run; consumer examples on this page were not recompiled.

The restored Pkcs versions are 8.0.2 / 9.0.22 / 10.0.14, matching configuration and packaged dependency groups, with no NU1603/NU1902/NU1903 warnings. SQLitePCLRaw.bundle_e_sqlite3 resolves transitively to 2.1.12 for all targets. This does not replace subsequent dependency vulnerability audits.