Complete reference for all public types, methods, and properties in XpressData.
Manages database connections and executes SQL commands.
public class DatabaseConnection : IDatabaseConnection, IDisposable, IAsyncDisposable| Method | Description |
|---|---|
Select(Query query) |
Executes a SELECT query and returns a SelectQueryResult |
Insert(Query query) |
Executes an INSERT command and returns an InsertQueryResult |
Update(Query query) |
Executes an UPDATE command and returns an UpdateQueryResult |
Execute(Query query) |
Executes a generic SQL command |
SelectScalar(Query query) |
Executes a query returning a single scalar value |
BeginTransaction() |
Begins a database transaction |
Commit() |
Commits the current transaction |
Rollback() |
Rolls back the current transaction |
All async methods support cancellation via CancellationToken.
| Method | Description |
|---|---|
SelectAsync(Query query, CancellationToken ct = default) |
Asynchronously executes a SELECT query |
InsertAsync(Query query, CancellationToken ct = default) |
Asynchronously executes an INSERT command |
UpdateAsync(Query query, CancellationToken ct = default) |
Asynchronously executes an UPDATE command |
ExecuteAsync(Query query, CancellationToken ct = default) |
Asynchronously executes a generic SQL command |
SelectScalarAsync(Query query, CancellationToken ct = default) |
Asynchronously executes a scalar query |
DeleteDatabaseAsync(CancellationToken ct = default) |
Asynchronously deletes the database |
DisposeAsync() |
Asynchronously disposes resources |
// Basic async query
await using var connection = new DatabaseConnection(dbInfo);
var result = await connection.SelectAsync(new Query("SELECT * FROM Users"));
// With cancellation support
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var users = await connection.SelectAsync(
new Query("SELECT * FROM Users WHERE Active = @Active",
new QueryParameter("Active", true)),
cts.Token);
// Async insert
var insertResult = await connection.InsertAsync(
new Query("INSERT INTO Users (Name, Email) VALUES (@Name, @Email)",
new QueryParameter("Name", "John"),
new QueryParameter("Email", "john@example.com")));
// Async update with affected row count
var updateResult = await connection.UpdateAsync(
new Query("UPDATE Users SET Active = @Active WHERE Id = @Id",
new QueryParameter("Active", false),
new QueryParameter("Id", 1)));
Console.WriteLine($"Rows affected: {updateResult.AffectedRows}");Contains database connection configuration.
public class DatabaseInformationpublic DatabaseInformation(
string server,
string database,
string? userId = null,
string? password = null,
bool? encrypt = null,
bool? trustServerCertificate = null,
int? connectionTimeout = null,
int? commandTimeout = null)| Property | Type | Description |
|---|---|---|
Server |
string |
Database server hostname |
Database |
string |
Database name |
UserId |
string? |
SQL authentication user ID |
Password |
string? |
SQL authentication password |
ConnectionString |
string |
Generated connection string |
// Parse from existing connection string
public static DatabaseInformation FromConnectionString(string connectionString)Represents a SQL query with parameters.
public class Query// Query without parameters
public Query(string commandText)
// Query with single parameter
public Query(string commandText, QueryParameter parameter)
// Query with multiple parameters
public Query(string commandText, params QueryParameter[] parameters)Represents a SQL parameter.
public class QueryParameterpublic QueryParameter(
string field,
object? value,
IQueryParameterHelper? helper = null,
string? typeName = null)Static factory class for creating type-safe SQL expressions.
public static class Builder// Create a field reference
public static ExpressionField Field(FieldMap fieldMap, Alias? alias = null)
// Create a value expression
public static ExpressionValue Value(object value)
// Create a values collection (for IN clauses)
public static ExpressionValuesCollection<T> Values<T>(IEnumerable<T> values)
// Create a values collection with TVP support
public static ExpressionValuesCollectionEx<T> ValuesEx<T>(IEnumerable<T> values)All comparison methods require proper interface casting for type safety.
// Numeric comparisons
public static ExpressionEqual Equal(IExpressionNumeric left, IExpressionNumeric right)
public static ExpressionMoreThan MoreThan(IExpressionNumeric left, IExpressionNumeric right)
public static ExpressionLessThan LessThan(IExpressionNumeric left, IExpressionNumeric right)
public static ExpressionMoreThanOrEqual MoreThanOrEqual(IExpressionNumeric left, IExpressionNumeric right)
public static ExpressionLessThanOrEqual LessThanOrEqual(IExpressionNumeric left, IExpressionNumeric right)
// String comparisons
public static ExpressionEqual Equal(IExpressionString left, IExpressionString right)
public static ExpressionNotEqual NotEqual(IExpressionString left, IExpressionString right)
public static ExpressionLike Like(IExpressionString left, IExpressionString right)
// GUID comparisons
public static ExpressionEqual Equal(IExpressionGuid left, IExpressionGuid right)
// Date comparisons
public static ExpressionMoreThanOrEqual MoreThanOrEqual(IExpressionDate left, IExpressionDate right)
public static ExpressionLessThanOrEqual LessThanOrEqual(IExpressionDate left, IExpressionDate right)
// DateTime comparisons
public static ExpressionMoreThanOrEqual MoreThanOrEqual(IExpressionDateTime left, IExpressionDateTime right)
public static ExpressionLessThanOrEqual LessThanOrEqual(IExpressionDateTime left, IExpressionDateTime right)public static ExpressionAnd And(IExpressionLogical left, IExpressionLogical right)
public static ExpressionOr Or(IExpressionLogical left, IExpressionLogical right)
public static ExpressionNot Not(IExpressionLogical single)public static ExpressionIsNull IsNull(IExpressionAny single)
public static ExpressionIsNotNull IsNotNull(IExpressionAny single)public static ExpressionIn In(IExpressionComperable left, IExpressionCollection right, bool inversed = false)
public static ExpressionIn NotIn(IExpressionComperable left, IExpressionCollection right)public static ExpressionAdd Add(IExpressionNumeric left, IExpressionNumeric right)
public static ExpressionMinus Minus(IExpressionNumeric left, IExpressionNumeric right)public static ExpressionAssign Assign(ILeftSide left, IExpressionAny right)public static OrderByInfo OrderBy(FieldMap fieldMap, EOrder order = EOrder.Asc, OrderByInfo? next = null)| Interface | Description | Use With |
|---|---|---|
IExpressionNumeric |
Numeric operations | int, long, decimal fields |
IExpressionString |
String operations | varchar, nvarchar fields |
IExpressionGuid |
GUID operations | uniqueidentifier fields |
IExpressionDate |
Date operations | date fields |
IExpressionDateTime |
DateTime operations | datetime fields |
IExpressionLogical |
Logical operations | Comparison results, AND/OR |
IExpressionComperable |
IN/NOT IN operations | Fields for collection checks |
IExpressionAny |
General operations | Null checks, assignments |
IExpressionCollection |
Collection expressions | Values collections |
Base class for entity-to-table mapping.
public class EntityMap<T> : BaseEntityMap where T : class, new()| Property | Type | Description |
|---|---|---|
EntityType |
Type |
The .NET type being mapped |
PhysicalTableName |
string |
Database table name |
Fields |
List<FieldMap> |
Collection of field mappings |
PrimaryKeyField |
FieldMap? |
Primary key field |
// Read operations
public T[] Get(IDatabaseConnection connection, IEnumerable<FieldMap>? view = null,
IExpressionLogical? filterExpression = null, OrderByInfo? orderByInfo = null,
long limit = 0, long offset = 0)
public T? GetByPrymaryKey(IDatabaseConnection connection, object primaryKeyValue,
IEnumerable<FieldMap>? view = null)
public long GetCount(IDatabaseConnection connection, Join? join = null,
Alias? alias = null, IExpressionLogical? filterExpression = null)
// Write operations
public void Insert(IDatabaseConnection connection, T newEntity)
public T InsertAndReturn(IDatabaseConnection connection, T newEntity)
public object? InsertAndReturnIdentity(IDatabaseConnection connection, T newEntity)
public void Update(IDatabaseConnection connection, T entity)
public void UpdateMany(IDatabaseConnection connection, IEnumerable<IAssign> assignments,
IExpressionLogical? criteriaExpression = null)
public void Delete(IDatabaseConnection connection, T deletedEntity)
public void DeleteMany(IDatabaseConnection connection, IExpressionLogical? criteriaExpression = null)All async methods support cancellation via CancellationToken.
// Async read operations
public Task<T[]> GetAsync(IDatabaseConnection connection, IEnumerable<FieldMap>? view = null,
IExpressionLogical? filterExpression = null, OrderByInfo? orderByInfo = null,
long limit = 0, long offset = 0, CancellationToken cancellationToken = default)
public Task<T?> GetByPrymaryKeyAsync(IDatabaseConnection connection, object primaryKeyValue,
IEnumerable<FieldMap>? view = null, CancellationToken cancellationToken = default)
public Task<long> GetCountAsync(IDatabaseConnection connection, Join? join = null,
Alias? alias = null, IExpressionLogical? filterExpression = null,
CancellationToken cancellationToken = default)
// Async write operations
public Task InsertAsync(IDatabaseConnection connection, T newEntity,
CancellationToken cancellationToken = default)
public Task<T> InsertAndReturnAsync(IDatabaseConnection connection, T newEntity,
CancellationToken cancellationToken = default)
public Task<object?> InsertAndReturnIdentityAsync(IDatabaseConnection connection, T newEntity,
CancellationToken cancellationToken = default)
public Task UpdateAsync(IDatabaseConnection connection, T entity,
CancellationToken cancellationToken = default)
public Task UpdateManyAsync(IDatabaseConnection connection, IEnumerable<IAssign> assignments,
IExpressionLogical? criteriaExpression = null, CancellationToken cancellationToken = default)
public Task DeleteAsync(IDatabaseConnection connection, T deletedEntity,
CancellationToken cancellationToken = default)
public Task DeleteManyAsync(IDatabaseConnection connection, IExpressionLogical? criteriaExpression = null,
CancellationToken cancellationToken = default)
// Async DDL operations
public Task CreateDatabaseTableAsync(IDatabaseConnection connection, bool dropTableFirst = false,
CancellationToken cancellationToken = default)
public Task TruncateAsync(IDatabaseConnection connection, CancellationToken cancellationToken = default)// Define an entity map
public class UserMap : EntityMap<User>
{
public override void InitializeMap()
{
PhysicalTableName = "Users";
var idField = new FieldMap(this, new FieldTypeInteger(), "Id", "id");
AddField(idField, isPrymaryKey: true);
AddField(new FieldMap(this, new FieldTypeString(100), "Name", "name"));
AddField(new FieldMap(this, new FieldTypeString(255), "Email", "email"));
}
}
// Async CRUD operations
var userMap = new UserMap();
await using var connection = new DatabaseConnection(dbInfo);
// Async Get with filter
var filter = Builder.Equal(
(IExpressionNumeric)Builder.Field(userMap.PrimaryKeyField!),
(IExpressionNumeric)Builder.Value(1));
var users = await userMap.GetAsync(connection, filterExpression: filter);
// Async Insert
var newUser = new User { Name = "Alice", Email = "alice@example.com" };
await userMap.InsertAsync(connection, newUser);
// Async Insert and get all generated values (auto-increment ID, computed columns, etc.)
var insertedUser = await userMap.InsertAndReturnAsync(connection, newUser);
Console.WriteLine($"Generated ID: {insertedUser.Id}");
// Or if you only need the identity value (more efficient)
var identityValue = await userMap.InsertAndReturnIdentityAsync(connection, newUser);
int generatedId = Convert.ToInt32(identityValue);
// Async Update
existingUser.Name = "Updated Name";
await userMap.UpdateAsync(connection, existingUser);
// Async Delete
await userMap.DeleteAsync(connection, userToDelete);
// With cancellation token
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));
var allUsers = await userMap.GetAsync(connection, cancellationToken: cts.Token);Represents mapping between entity property and database column.
public class FieldMap| Property | Type | Description |
|---|---|---|
Name |
string |
Entity property name |
PhysicalName |
string |
Database column name |
FieldType |
FieldType |
SQL type information |
IsNullable |
bool |
Whether column allows NULL |
IsAutoIncrement |
bool |
Whether column is auto-incrementing (IDENTITY) |
IsPK |
bool |
Whether this is the primary key |
IsFK |
bool |
Whether this is a foreign key |
DelimitedPhysicalName |
string |
Delimited column name (e.g., [ColumnName]) |
SqlColumnDefinition |
string |
Complete SQL column definition for DDL |
Auto-increment fields are automatically populated by the database using SQL Server's IDENTITY feature:
// Integer primary key with auto-increment
var idField = new FieldMap(
this,
new FieldTypeInteger(),
"Id",
"id",
isNullable: false,
isAutoIncrement: true // Enable IDENTITY(1,1)
);
AddField(idField, isPrymaryKey: true);Supported Auto-Increment Types:
FieldTypeInteger(int)FieldTypeBigInt(bigint)FieldTypeNumeric(numeric)
INSERT Behavior: Auto-increment fields are automatically skipped during INSERT operations, allowing the database to generate values.
var entity = new MyEntity
{
Id = 0, // Will be ignored
Name = "Test"
};
entityMap.Insert(connection, entity);Available field type classes for SQL Server data types:
| Class | SQL Type | .NET Type | AutoIncrement Support |
|---|---|---|---|
FieldTypeInteger |
[int] |
int |
✓ Yes |
FieldTypeBigInt |
[bigint] |
long |
✓ Yes |
FieldTypeNumeric(precision, scale) |
[numeric](p,s) |
decimal |
✓ Yes |
FieldTypeString(length) |
[varchar](n) |
string |
✗ No |
FieldTypeFixedString(length) |
[nchar](n) |
string |
✗ No |
FieldTypeGuid |
[uniqueidentifier] |
Guid |
✗ No |
FieldTypeBoolean |
[bit] |
bool |
✗ No |
FieldTypeDateTime |
[datetime] |
DateTime |
✗ No |
FieldTypeDate |
[date] |
DateTime |
✗ No |
FieldTypeBinary(length) |
[varbinary](n) |
byte[] |
✗ No |
FieldTypeFixedBinary(length) |
[binary](n) |
byte[] |
✗ No |
// Basic registration
services.AddXpressData(Configuration.GetSection("XpressData"));
// With custom database implementation
services.AddXpressData<MyCustomDatabase>(Configuration.GetSection("XpressData"));
// With action configuration
services.AddXpressData(options =>
{
options.ConnectionString = "Server=localhost;Database=MyDb;...";
options.LiteMode = false;
});public class XpressDataOptions
{
public string? ConnectionString { get; set; }
public string? Server { get; set; }
public string? Database { get; set; }
public string? UserId { get; set; }
public string? Password { get; set; }
public bool Encrypt { get; set; }
public bool TrustServerCertificate { get; set; }
public int ConnectionTimeout { get; set; }
public int CommandTimeout { get; set; }
public bool LiteMode { get; set; }
}{
"XpressData": {
"Server": "localhost",
"Database": "MyDatabase",
"UserId": "sa",
"Password": "YourPassword",
"TrustServerCertificate": true,
"CommandTimeout": 30,
"LiteMode": false
}
}