Orchard Core Data - Prompt Templates
Configure and Use the Orchard Core Data Layer
You are an Orchard Core expert. Generate code and configuration for database access, YesSql settings, Dapper queries, connection management, and table prefix handling.
Guidelines
- Orchard Core uses YesSql (6.3.0 in Orchard Core 4.0) as its document database abstraction over relational databases. Map index providers declare
ExclusiveToDocumentType()andSingleRecordPerDocument()when true, andIQuery<T>.NoDuplicates()is obsolete in favor ofSkipDeduplication(); seeorchardcore-yessql-indexes. - Supported database providers:
Sqlite(default),SqlConnection(SQL Server),Postgres,MySql. For SQL Server, MySQL and PostgreSQL, create the database first; Orchard Core creates the tables, not the database. - Provider, connection string, table prefix and schema are tenant settings (setup screen or
IShellConfiguration). - Prefer
IContentManagerfor content items andISessionfor YesSql documents and indexes; use raw SQL only for custom relational tables. - Use
IDbConnectionAccessor(OrchardCore.Data, packageOrchardCore.Data.Abstractions) to createDbConnectioninstances pointing to the tenant database. - Use
IStore.Configurationfor theSqlDialect,TablePrefix(already includes the separator) andSchema. - Quote table names with
dialect.QuoteForTableName(name, schema)so tenants with a schema work too. - Never pass user input into identifiers; pass data values as Dapper parameters.
- Create custom tables through data migrations (see
orchardcore-data-migrations). - Configuration sections are nested under
OrchardCoreand, since Orchard Core 4.0, are namedYesSql,Data:Sqlite,Data:TableOptionsandDocuments. - All recipe JSON must be wrapped in
{ "steps": [...] }. - All C# classes must use the
sealedmodifier, except view models.
Sqlite Options
The DatabaseName shell setting controls the SQLite file name (OrchardCore.db by default) in the tenant's data folder.
Microsoft.Data.Sqlite pools connections by default. Disable it when file locking interferes with copying or replacing the database file (for example backups); this can reduce performance:
{
"OrchardCore": {
"Data": {
"Sqlite": {
"UseConnectionPooling": false
}
}
}
}
YesSql Configuration Options
OrchardCore:YesSql binds to YesSqlOptions (namespace OrchardCore.Data.YesSql).
| Setting | Description | Default |
|---|---|---|
| CommandsPageSize | Max commands per command page before YesSql splits them | 500 |
| QueryGatingEnabled | Coalesces identical concurrent queries and shares the result | true |
| EnableThreadSafetyChecks | Helps diagnose concurrent use of a session | false |
| IsolationLevel | Default transaction isolation level | ReadCommitted |
| ConcurrentIndexCreationEnabled | Creates the indexes a data migration adds to an existing table without blocking writes: online on SQL Server editions that support online index operations (Enterprise, Developer, Azure SQL Database, Azure SQL Managed Instance) and with ALGORITHM=INPLACE, LOCK=NONE on MySQL. PostgreSQL still blocks writes (migrations run in a transaction) and SQLite creates indexes the regular way. Set to false to always create them the regular way | true |
| IncludeQueryTextInTelemetry | Adds the SQL text (db.query.text) to YesSql command spans when the YesSql telemetry source is collected (see orchardcore-opentelemetry). Raw SQL fragments are included as is and can expose data to the telemetry receiver | false |
IdGenerator, IdentifierAccessorFactory, VersionAccessorFactory and ContentSerializer can only be set in code.
Configure YesSql in appsettings.json
{
"OrchardCore": {
"YesSql": {
"CommandsPageSize": 1000,
"QueryGatingEnabled": true,
"EnableThreadSafetyChecks": false,
"IsolationLevel": "ReadCommitted",
"ConcurrentIndexCreationEnabled": true,
"IncludeQueryTextInTelemetry": false
}
}
}
In a tenant-local App_Data/Sites/{tenant}/appsettings.json, omit the outer OrchardCore section.
Configure YesSql in Code
using OrchardCore.Data.YesSql;
public sealed class Startup : StartupBase
{
public override void ConfigureServices(IServiceCollection services)
{
services.Configure<YesSqlOptions>(options =>
{
options.CommandsPageSize = 1000;
});
}
}
Database Table Options
OrchardCore:Data:TableOptions holds presets copied into a tenant's shell settings during initial setup. Changing them later doesn't rename existing tables or alter identity columns.
| Setting | Description | Default |
|---|---|---|
| DefaultDocumentTable | Document table name | Document |
| DefaultTableNameSeparator | Separator between prefix/collection and table name (one or more _, or NULL for none) | _ |
| DefaultIdentityColumnSize | Identity column size (Int32 or Int64) | Int64 |
{
"OrchardCore": {
"Data": {
"TableOptions": {
"DefaultDocumentTable": "Document",
"DefaultTableNameSeparator": "_",
"DefaultIdentityColumnSize": "Int64"
}
}
}
}
Document Options
OrchardCore:Documents sets the shared options of the documents managed by IDocumentManager<TDocument> (site settings, content definitions, ...): CheckConcurrency and CheckConsistency (default true), SynchronizationLatency (default 1 second), FailoverRetryLatency (default 30 seconds), CompressThreshold (default 10,000 characters), and LockTimeout/LockExpiration (default 10,000 ms, atomic updates only).
{
"OrchardCore": {
"Documents": {
"SynchronizationLatency": "00:00:02"
}
}
}
Creating a DbConnection
using Dapper;
using OrchardCore.Data;
using YesSql;
public sealed class MyDataService
{
private readonly IDbConnectionAccessor _dbAccessor;
private readonly IStore _store;
public MyDataService(IDbConnectionAccessor dbAccessor, IStore store)
{
_dbAccessor = dbAccessor;
_store = store;
}
public async Task<int> GetRecordCountAsync(CancellationToken cancellationToken)
{
await using var connection = _dbAccessor.CreateConnection();
await connection.OpenAsync(cancellationToken);
var configuration = _store.Configuration;
var table = configuration.SqlDialect.QuoteForTableName($"{configuration.TablePrefix}MyTable", configuration.Schema);
return await connection.ExecuteScalarAsync<int>(
new CommandDefinition($"SELECT COUNT(*) FROM {table}", cancellationToken: cancellationToken));
}
}
SQL Dialect Abstraction
using Dapper;
using OrchardCore.Data;
using YesSql;
public sealed class ProductRepository
{
private readonly IDbConnectionAccessor _dbAccessor;
private readonly IStore _store;
public ProductRepository(IDbConnectionAccessor dbAccessor, IStore store)
{
_dbAccessor = dbAccessor;
_store = store;
}
public async Task<IReadOnlyList<ProductRecord>> GetByCategoryAsync(string category, CancellationToken cancellationToken)
{
await using var connection = _dbAccessor.CreateConnection();
await connection.OpenAsync(cancellationToken);
var configuration = _store.Configuration;
// TablePrefix already contains the separator; pass the schema when quoting.
var tableName = configuration.SqlDialect.QuoteForTableName(
$"{configuration.TablePrefix}ProductRecord",
configuration.Schema);
var command = new CommandDefinition(
$"SELECT * FROM {tableName} WHERE Category = @Category",
new { Category = category },
cancellationToken: cancellationToken);
return (await connection.QueryAsync<ProductRecord>(command)).AsList();
}
}
Dapper with Transactions
Open the connection before beginning the transaction, pass the transaction to every command, and rethrow after rollback:
using Dapper;
using OrchardCore.Data;
using YesSql;
public sealed class OrderService
{
private readonly IDbConnectionAccessor _dbAccessor;
private readonly IStore _store;
public OrderService(IDbConnectionAccessor dbAccessor, IStore store)
{
_dbAccessor = dbAccessor;
_store = store;
}
public async Task ChangeStatusAsync(int orderId, string newStatus, CancellationToken cancellationToken)
{
var configuration = _store.Configuration;
var dialect = configuration.SqlDialect;
var ordersTable = dialect.QuoteForTableName($"{configuration.TablePrefix}Orders", configuration.Schema);
var auditTable = dialect.QuoteForTableName($"{configuration.TablePrefix}OrderAudit", configuration.Schema);
await using var connection = _dbAccessor.CreateConnection();
await connection.OpenAsync(cancellationToken);
await using var transaction = await connection.BeginTransactionAsync(cancellationToken);
try
{
await connection.ExecuteAsync(new CommandDefinition(
$"UPDATE {ordersTable} SET Status = @Status WHERE Id = @Id",
new { Status = newStatus, Id = orderId },
transaction,
cancellationToken: cancellationToken));
await connection.ExecuteAsync(new CommandDefinition(
$"INSERT INTO {auditTable} (OrderId, Action, Timestamp) VALUES (@OrderId, @Action, @Timestamp)",
new { OrderId = orderId, Action = $"Status changed to {newStatus}", Timestamp = DateTime.UtcNow },
transaction,
cancellationToken: cancellationToken));
await transaction.CommitAsync(cancellationToken);
}
catch
{
await transaction.RollbackAsync(cancellationToken);
throw;
}
}
}
Handling Table Prefixes
Each tenant can have a table prefix and a schema. Read them from IStore.Configuration (TablePrefix includes the separator, Schema may be null) rather than from ShellSettings["TablePrefix"], which lacks the separator.
Upgrading from 3.x
OrchardCore_YesSqlis nowOrchardCore:YesSql.OrchardCore_Data_Sqliteis nowOrchardCore:Data:Sqlite.OrchardCore_Data_TableOptionsis nowOrchardCore:Data:TableOptions.OrchardCore_Documentsis nowOrchardCore:Documents.- The old names are deprecated but still read; when both exist, the new name wins. Environment variables follow the same shape, for example
OrchardCore__YesSql__CommandsPageSize. The packages ship aConfigurationSchema.jsonthat givesappsettings.jsonIntelliSense and flags deprecated names.