| Branch | Status |
|---|---|
| main |
SharpPersistence
SharpPersistence is a collection of robust, extensible, and thoroughly tested .NET libraries for working with database systems.
Installation
To install the packages, run the following commands:
dotnet add package SharpPersistence.Abstractions
dotnet add package SharpPersistence
dotnet add package SharpPersistence.EfCore
Or visit:
Features
SqlParser
SqlParseris available inSharpPersistence- Separation of Concerns: Keep complex SQL queries in
.sqlfiles instead of cluttering your C# code - Better SQL Editing: Full syntax highlighting, IntelliSense, and formatting in SQL files
- Version Control Friendly: Track SQL changes separately from business logic
- Team Collaboration: Database developers can work on SQL files while C# developers focus on application logic
- Compile-Time Safety: Parse and validate SQL files at application startup, catching errors early
Basic Usage
1. Create SQL files with tagged blocks:
- SQL statements must be enclosed by
-- #start# TagNameand-- #end# TagNamecomments. - Unique tag of a sql statement is case-insensitive.
-- #start# GetAllUsers
SELECT u.Id, u.Name, u.Email, u.CreatedAt
FROM Users u
WHERE u.Id = :userId
ORDER BY u.Name
-- #end# GetAllUsers
-- #start# GetActiveUsers
SELECT u.Id, u.Name, u.Email
FROM Users u
WHERE u.IsActive = 1 AND u.IsDeleted = 0
ORDER BY u.LastLoginDate DESC
-- #end# GetActiveUsers
2. Configure your project to copy SQL files:
- Create a file named
Directory.Build.propsat the same level of yourslnorslnxfile. - Copy and paste the following code in the
Directory.Build.propsfile. - If you already have
Directory.Build.props, then copy the code inside<Project> </Project>
<Project>
<PropertyGroup>
<DefaultItemExcludes>
$(DefaultItemExcludes);out/**;publish/**;bin/**;obj/**
</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<Content Include="**\*.sql"
Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)"
CopyToOutputDirectory="PreserveNewest"
TargetPath="sharp_persistence_sql_files\$(AssemblyName)\%(RecursiveDir)\%(Filename)%(Extension)"/>
</ItemGroup>
</Project>
- Alternatively, if you want to handle it from
csprojfile, Add the following code to yourcsprojfile’s<Project> </Project>node.
<PropertyGroup>
<DefaultItemExcludes>
$(DefaultItemExcludes);out/**;publish/**;bin/**;obj/**
</DefaultItemExcludes>
</PropertyGroup>
<ItemGroup>
<Content Include="**\*.sql"
Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)"
CopyToOutputDirectory="PreserveNewest"
TargetPath="sharp_persistence_sql_files\$(AssemblyName)\%(RecursiveDir)\%(Filename)%(Extension)"/>
</ItemGroup>
sharp_persistence_sql_filesis the default directory. If you want to change it, make sure to pass the new value in theParseFromStorage()method’s parameter. The same value must be used in theTargetPathof the above code.
3. Parse and use in your application:
// Parse SQL files at startup
IParsedSqlStorage parsedSqlStorage = new SqlParser().ParseFromStorage();
// Access parsed SQL by tag name (case-insensitive) through C# indexer
string getAllUsersQuery = parsedSqlStorage["GetAllUsers"];
// Use the query...
// Safe access with TryGet
if (parsedSqlStorage.TryGetParsedSql("GetAllUsers", out string? query))
{
// Use the query...
}
4. Dependency Injection (ASP.NET Core):
// In Program.cs
IParsedSqlStorage parsedSqlStatements = new SqlParser().ParseFromStorage();
builder.Services.AddSingleton<IParsedSqlStorage>(parsedSqlStatements);
// In your service classes
public class UserService
{
private readonly IDbConnectionFactory _dbConnectionFactory;
private readonly IParsedSqlStorage _parsedSqlStorage;
public UserService(IDbConnectionFactory dbConnectionFactory, IParsedSqlStorage parsedSqlStorage)
{
_dbConnectionFactory = dbConnectionFactory;
_parsedSqlStorage = parsedSqlStorage;
}
public async Task<IEnumerable<User>> GetAllUsersAsync(int userId, CancellationToken ct)
{
var sql = _parsedSqlStorage["GetAllUsers"];
await using var connection = await _dbConnectionFactory.CreateConnectionAsync(ct);
var parameters = new { userId };
return await connection.QueryAsync<User>(new CommandDefinition(sql, parameters,
cancellationToken: ct));
}
}
Notes: SqlParser validates your SQL files at startup and throws detailed error messages for:
- Missing start/end tags
- Duplicate tag names
- Invalid tag formats
SqlCheckConstraintBuilder
SqlCheckConstraintBuilderis available inSharpPersistence(using SharpPersistence;+using SharpPersistence.Enums;).- Replaces the obsolete
SqlCheckConstraintGenerator,Rdbms, andSqlNamingConventiontypes. - Compile-time type safety:
.Math()is only available on numeric columns (INumber<T>),.Length()/.Trim()/.Lower()/.Upper()/.Like()only onstringcolumns, andCase()enforcesWhen -> Then -> End / EndWithElseordering. - Supports PostgreSQL, MySQL, SQL Server, Oracle, and SQLite.
- Supports
PascalCase,lower_snake_case, andUPPER_SNAKE_CASEidentifier casing. - Every predicate/built expression implicitly converts to
string(HasCheckConstraint("name", expr)orstring sql = expr;)—there is no.Build()method.
Setup
var cc = new SqlCheckConstraintBuilder
{
Dialect = SqlDialect.PostgreSql, // PostgreSql | MySql | SqlServer | Oracle | Sqlite
IdentifierCase = SqlIdentifierCase.LowerSnakeCase, // PascalCase | LowerSnakeCase | UpperSnakeCase
DelimitIdentifiers = true, // required
NestedSeparator = "_" // optional, default "_"
};
Column Selection & Operations
- Avoid lambda parameter shadowing: When nesting inside
builder.ToTable(t => ...), use a distinct parameter name inColumn(...)(e.g.,tfor the table builder andxorefor the entity) instead of reusingxin both lambdas. entity.Column(x => x.Prop): Single-level properties only (throwsArgumentExceptionon nested chains).entity.NestedColumn(x => x.Address.Country): Owned/nested properties, joined withNestedSeparatorand transformed byIdentifierCase.cc.RawColumn<TProp>("col_name"): Shadow or custom-named DB columns. IgnoresIdentifierCase(preserves exact casing; still respectsDelimitIdentifiers/.WithDelimiter()/.WithoutDelimiter()).- Comparisons (value or lambda/column):
EqualTo,NotEqualTo,GreaterThan,GreaterThanOrEqual,LessThan,LessThanOrEqual,Between,NotBetween,In,NotIn,IsNull,IsNotNull.EqualTo(null)/NotEqualTo(null)renderIS NULL/IS NOT NULL. - String (
stringcolumns only):.Length()(comparisons only),.Trim(),.Lower(),.Upper(),.Like(pattern),.NotLike(pattern). - Arithmetic (
INumber<T>/INumber<T>?columns only):.Math()unlocks.Plus(...),.Minus(...),.MultiplyBy(...),.DivideBy(...),.Modulo(...), and.Abs(). - Coalesce & Value Converters:
.Coalesce(fallbackValue | x => x.FallbackColumn),.EnumAsString()/.EnumAsNumeric(),.BoolAsNumeric()(re-typesbooltointfor.EqualTo(1)/.EqualTo(0)),.BoolAsString()(re-typesbooltostringfor.EqualTo("Y")). - Logical, Conditional &
CASE:cc.And(...),cc.Or(...),.And(...),.Or(...),.Not(),cc.If(condition).Then(requirement)(renders(NOT (condition) OR requirement), works in all dialects including Oracle),cc.RawPredicate("..."), andcc.Case().When(predicate).Then(then).EndWithElse(elseExpr)/.End().
Examples with EF Core IEntityTypeConfiguration
var cc = new SqlCheckConstraintBuilder
{
Dialect = SqlDialect.PostgreSql,
IdentifierCase = SqlIdentifierCase.LowerSnakeCase,
DelimitIdentifiers = false
};
var order = cc.For<Order>();
builder.ToTable(t =>
{
t.HasCheckConstraint("ck_order_country",
order.NestedColumn(x => x.ShippingAddress.Country).Length().In(2, 3));
t.HasCheckConstraint("ck_order_net_total",
order.Column(x => x.Subtotal).Math().Minus(order.Column(x => x.Discount).Coalesce(0m).Math()).GreaterThan(0));
t.HasCheckConstraint("ck_order_status",
order.Column(x => x.Status).EnumAsString().In(OrderStatus.Draft, OrderStatus.Confirmed));
t.HasCheckConstraint("ck_order_priority",
order.Column(x => x.IsPriority).BoolAsNumeric().EqualTo(1));
t.HasCheckConstraint(
"ck_order_shipped_at",
cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Shipped))
.Then(order.Column(x => x.ShippedAt).IsNotNull())
);
// Multi-branch conditional rule via cc.If(...).Then(...) (all dialects including Oracle)
t.HasCheckConstraint(
"ck_order_status_timestamps",
cc.And(
cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Shipped))
.Then(order.Column(x => x.ShippedAt).IsNotNull()),
cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Cancelled))
.Then(order.Column(x => x.CancelledAt).IsNotNull())
)
);
// Multi-branch CASE (for PostgreSQL/MySQL; for Oracle prefer cc.If(...).Then(...))
t.HasCheckConstraint(
"ck_order_discount_tier",
cc.Case()
.When(order.Column(x => x.Total).GreaterThan(100m))
.Then(order.Column(x => x.Discount).LessThanOrEqual(50m))
.EndWithElse(order.Column(x => x.Discount).LessThanOrEqual(10m))
);
t.HasCheckConstraint("ck_order_tenant",
cc.RawColumn<Guid>("tenant_id").NotEqualTo(Guid.Empty));
});
RepositoryCore with IRepositoryCore
IRepositoryCoreis available inSharpPersistence.AbstractionsRepositoryCoreis available inSharpPersistence.EfCore- Prefer this for all new code: CRUD, tracking (
TrackEntity/TrackEntities), bulk delete (RemoveManyDirectAsync/RemoveManyDirectIgnoringFiltersAsync), andQuery()(noGet*overload grid) Query()returnsIEntityQuery<T>for composable reads (Where,OrderBy,OrderByDesc,EnableTracking,IgnoreQueryFilters,OffsetPaginate,Select,GetFirstOrDefaultAsync,GetFirstOrNullAsync,GetAllAsync,GetCountAsync,ExistsAsync,EveryAsync,SumAsync,MinAsync,MaxAsync,MinOrNullAsync,MaxOrNullAsync)- Set tracking on the entity query before
Select; after projection, tracking methods do nothing
// Register / inject IRepositoryCore<User> (or your derived interface)
var allData = await repo.Query()
.Where(u => u.IsActive)
.OrderBy(u => u.Name)
.OffsetPaginate(page: 1, limit: 20)
.Select(u => new { u.Id, u.Name })
.GetAllAsync(ct);
var singleData = await repo.Query()
.Where(u => u.Id == id)
.EnableTracking()
.GetFirstOrDefaultAsync(ct);
bool hasPending = await repo.Query()
.Where(u => u.IsActive)
.ExistsAsync(u => u.IsPending, ct);
int deleted = await repo.RemoveManyDirectAsync(u => !u.IsActive, ct);
int purged = await repo.RemoveManyDirectIgnoringFiltersAsync(
u => u.IsDeleted,
[AppDbContext.SoftDeleteFilter],
ct);
// Aggregates (single column or computed expression)
decimal total = await orderRepo.Query()
.Where(x => x.IsPaid)
.SumAsync(x => x.Total, ct);
decimal netTotal = await orderRepo.Query()
.Where(x => x.IsPaid)
.SumAsync(x => x.Subtotal - x.Discount, ct);
DateTime? latestOrderAt = await orderRepo.Query()
.Where(x => x.CustomerId == customerId)
.MaxOrNullAsync(x => x.CreatedAt, ct);
RepositoryBase with IRepositoryBase (Obsolete)
- Marked
[Obsolete("Use IRepositoryCore<TEntity> / RepositoryCore<TEntity, TDbContext> instead.")] IRepositoryBaseextendsIRepositoryCore(sameQuery+ CRUD surface, plus legacyGet*overloads)RepositoryBaseextendsRepositoryCoreand implementsIRepositoryBase- Existing consumers keep working, but new code should use
IRepositoryCore/RepositoryCore
// Legacy overload style (obsolete)
var user = await repo.GetOneAsync(u => u.IsActive);
// Recommended fluent query style (via IRepositoryCore)
var page = await repo.Query()
.Where(u => u.IsActive)
.OrderBy(u => u.Name)
.OffsetPaginate(page: 1, limit: 20)
.GetAllAsync(ct);
UnitOfWork with IUnitOfWork
IUnitOfWorkis available inSharpPersistence.AbstractionsUnitOfWorkis available inSharpPersistence.EfCore- Transactional management of multiple repository operations
- Ensures atomicity and consistency across changes
- Integrates seamlessly with the repository pattern
- Simplifies commit/rollback logic in service layers
Testing
- All features are covered by xUnit v3 and Shouldly assertions.
- Tests cover all overloads, edge cases, and RDBMS/naming convention combinations.
- To run tests:
dotnet test
Contributing
Contributions are welcome! Please open issues or submit pull requests for bug fixes, improvements, or new features.