ef-core-azure-sql

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

EF Core against Azure SQL Database

面向 Azure SQL Database 的 EF Core

This is the Azure SQL Database delta on top of EF Core, not an EF Core tutorial. Modelling, LINQ, change tracking and
Include
work the same everywhere and are not repeated here.
Command output, compiler results and runtime behaviour below are for
Microsoft.EntityFrameworkCore.SqlServer
9 unless a row says otherwise. EF Core 10 is the supported long term release and EF Core 9 is still serviced. Open references/retry-transactions-and-type-mapping.md when something below disagrees with what you are seeing, or to run the checks yourself.
本文介绍 EF Core 在 Azure SQL Database 基础上的差异部分,而不是 EF Core 教程。建模、LINQ、change tracking 和
Include
在各处的工作方式都相同,因此不再重复。
除非某一行另有说明,下文的命令输出、编译器结果和运行时行为均基于
Microsoft.EntityFrameworkCore.SqlServer
9。EF Core 10 是受支持的长期发布版本,EF Core 9 仍处于维护阶段。 如果下述内容与实际观察不符,或想自行运行检查,请打开 references/retry-transactions-and-type-mapping.md。

Scope

范围

  • The Azure SQL Database delta on EF Core, not general EF Core.
  • Pooling is
    connect-from-dotnet
    , retry doctrine
    connect-to-azure-sql
    , identity
    entra-id-auth
    , and running migrations from a pipeline
    github-actions-for-sql
    .
  • EF Core 相对通用实现的 Azure SQL Database 差异,而不是通用 EF Core 内容。
  • 连接池由
    connect-from-dotnet
    处理,retry 原则由
    connect-to-azure-sql
    处理,identity 由
    entra-id-auth
    处理,从 pipeline 运行 migration 则由
    github-actions-for-sql
    处理。

The correction

核心修正

Retry is not a setting on this database. Every current recommendation turns it on:
EnableRetryOnFailure
in older code,
UseAzureSql
in newer code. Both produce
SqlServerRetryingExecutionStrategy
, and turning it on silently redefines what a transaction is. The visible half is an exception, and it is not the problem. The problem is the code written next, because the exception dictates its own remedy and the remedy is incomplete:
csharp
// Retry on, so this unit is replayed on a transient fault. A fault arriving after
// Commit runs the delegate again, inserts the order a SECOND time, and Execute returns
// success. Nothing is thrown. Nothing is logged. The caller is told it worked.
var strategy = context.Database.CreateExecutionStrategy();
strategy.Execute(() =>
{
    using var tx = context.Database.BeginTransaction();
    context.Orders.Add(order);
    context.SaveChanges();
    tx.Commit();
});
A retriable unit is a unit that will be run more than once. Retry does not make a transaction resilient. It makes it repeatable, and a repeatable write that is not idempotent is a duplicate write waiting for a network fault it was configured to expect. Both call shapes carry this identically, so switching call does not fix it and staying on the old call does not cause it.
在这个数据库上,retry 并非一项可选设置。当前所有推荐做法都会启用它:旧代码使用
EnableRetryOnFailure
,新代码使用
UseAzureSql
。两者都会创建
SqlServerRetryingExecutionStrategy
,并且启用它会悄无声息地重新定义 transaction 的含义。看得见的部分是一个异常,但异常本身并不是问题。真正的问题在于异常之后编写的代码,因为异常已经决定了相应的补救方式,而这种补救并不完整:
csharp
// Retry on, so this unit is replayed on a transient fault. A fault arriving after
// Commit runs the delegate again, inserts the order a SECOND time, and Execute returns
// success. Nothing is thrown. Nothing is logged. The caller is told it worked.
var strategy = context.Database.CreateExecutionStrategy();
strategy.Execute(() =>
{
    using var tx = context.Database.BeginTransaction();
    context.Orders.Add(order);
    context.SaveChanges();
    tx.Commit();
});
**可重试的工作单元就是可能运行不止一次的工作单元。Retry 不会让 transaction 具备韧性。它会让 transaction 可重复执行,而不可幂等的可重复写入,就是一次重复写入,它在等待一个本就被配置为预期发生的网络故障。两种调用形式都同样存在这个问题,因此切换调用形式无法修复它,沿用旧调用形式也不会导致它。

What actually refuses, and what does not

究竟哪些操作会拒绝,哪些不会

The commonly repeated claim, that
Database.BeginTransaction
throws, is wrong.
Call, with the retrying strategy configuredResult
Database.BeginTransaction()
on its own
Succeeds. No exception
A LINQ query while that transaction is openThrows
InvalidOperationException
at once
SaveChanges
while that transaction is open
Throws
InvalidOperationException
at once
Database.ExecuteSqlRaw
while that transaction is open
Succeeds. Not guarded at all
SaveChanges
with no explicit transaction
Succeeds. EF's own transaction is a unit it created
The guard fires on EF's own pipeline, not on raw SQL, and on the first execution of the path rather than under load:
InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.
This exception is cheap: deterministic, milliseconds, on the first run of the path, and it names its own fix. Treat it as a compiler error that arrives late. The fix it names is not the whole fix, and nothing after it fails loudly. That is the next section, and it is why this skill exists.
人们经常重复声称
Database.BeginTransaction
会抛出异常,但这并不正确。
调用方式,已配置 retrying strategy结果
单独调用
Database.BeginTransaction()
**成功。**不会抛出异常
transaction 打开期间执行 LINQ query立即抛出
InvalidOperationException
transaction 打开期间执行
SaveChanges
立即抛出
InvalidOperationException
transaction 打开期间执行
Database.ExecuteSqlRaw
**成功。**完全没有受到保护
未使用显式 transaction 时执行
SaveChanges
成功。EF 自己创建的 transaction 构成一个工作单元
该保护机制作用于 EF 自身的 pipeline,而不作用于原始 SQL,并且会在该路径第一次执行时立即触发,而不是在负载压力下才触发:
InvalidOperationException: The configured execution strategy 'SqlServerRetryingExecutionStrategy' does not support user-initiated transactions. Use the execution strategy returned by 'DbContext.Database.CreateExecutionStrategy()' to execute all the operations in the transaction as a retriable unit.
这个异常的成本很低:它是确定性的,只需毫秒级时间,在路径首次执行时触发,并且会明确指出自己的修复方式。请把它视为一个延迟到达的编译错误。它指出的修复方式并不是完整的修复,而且后续操作不会显式报错。下一节将说明这一点,这也正是本 skill 存在的原因。

The silent duplicate write

静默的重复写入

Same delegate, same configured strategy, one variable: where the transient fault lands.
Fault arrivesDelegate runsRows committedWhat the caller sees
Before
Commit
21Success. Correct, the first attempt rolled back
After
Commit
22Success. No exception, no warning, no log line
The window is the commit acknowledgement. The commit reached the server, the acknowledgement did not reach the client, and the strategy cannot tell that apart from a commit that never happened, so it replays a unit that already succeeded. Learn calls this the idempotency issue and says it can lead to data corruption. The blast radius is a silent double write on a transactional path, in production only, on exactly the transient faults this database is configured to expect.
使用相同的 delegate 和相同的策略,只改变一个变量:瞬时故障发生的位置。
故障发生时机delegate 执行次数已提交行数调用方看到的结果
Commit
之前
21成功。第一次尝试已回滚,结果正确
Commit
之后
22成功。没有异常、没有警告,也没有日志
风险窗口就在 commit acknowledgement 环节:提交已经到达服务器,但确认没有到达客户端,而策略无法将其与从未发生的提交区分开来,因此会重放一个实际上已经成功的工作单元。Microsoft Learn 将此称为 idempotency 问题,并指出它可能导致 data corruption。其影响范围是 transaction 路径上的静默双写,只会在生产环境中发生,并且恰好发生在该数据库被配置为预期发生的瞬时故障上。

Making the unit safe to run twice

让工作单元可以安全运行两次

In order of preference.
  1. Give the write a natural idempotency key and a unique index, so a replay collides with
    Msg 2601
    instead of duplicating. This is the only defence that survives a process crash between the two attempts.
  2. Hand the transaction to
    ExecuteInTransaction
    with a
    verifySucceeded
    predicate.
    The strategy owns the transaction and, when the commit fails with an unknown outcome, asks the predicate whether the work already landed before retrying:
csharp
var strategy = db.Database.CreateExecutionStrategy();
db.Orders.Add(order);

await strategy.ExecuteInTransactionAsync(
    db,
    operation: (context, cancellationToken) =>
        context.SaveChangesAsync(acceptAllChangesOnSuccess: false, cancellationToken),
    verifySucceeded: (context, cancellationToken) =>
        context.Orders.AsNoTracking().AnyAsync(o => o.Key == order.Key, cancellationToken),
    cancellationToken: ct);

db.ChangeTracker.AcceptAllChanges();
acceptAllChangesOnSuccess: false
is load bearing, not decoration: it leaves the entity
Added
so the same unit can be replayed if the commit is what failed, and
AcceptAllChanges
afterwards is what finishes the save. The verifying context needs its own execution strategy, because the connection that just failed is likely to fail again during the check.
  1. Only then the bare
    CreateExecutionStrategy().ExecuteAsync
    wrapper, and only for units that are already safe to run twice. The delegate must not capture entities tracked by an outer context, must not rely on store generated keys, and must not send an email, enqueue a message or charge a card inside it.
Some units cannot be made idempotent, and for those the choice is to accept the duplicate risk or to narrow the retry set, never to disable retry so the exception goes away.
按优先级排列。
  1. 为写入提供天然的 idempotency key 和 unique index,这样重放时就会与
    Msg 2601
    冲突,而不是产生重复数据。这是唯一能够在两次尝试之间发生进程崩溃时仍然有效的防护。
  2. **将 transaction 交给
    ExecuteInTransaction
    ,并提供
    verifySucceeded
    predicate。**由策略管理 transaction;当 commit 以结果未知的方式失败时,策略会在 retry 前询问 predicate,以判断工作是否已经落库:
csharp
var strategy = db.Database.CreateExecutionStrategy();
db.Orders.Add(order);

await strategy.ExecuteInTransactionAsync(
    db,
    operation: (context, cancellationToken) =>
        context.SaveChangesAsync(acceptAllChangesOnSuccess: false, cancellationToken),
    verifySucceeded: (context, cancellationToken) =>
        context.Orders.AsNoTracking().AnyAsync(o => o.Key == order.Key, cancellationToken),
    cancellationToken: ct);

db.ChangeTracker.AcceptAllChanges();
acceptAllChangesOnSuccess: false
承担着关键作用,并非可有可无的装饰性参数:它会让 entity 保持
Added
状态,以便在 commit 失败时重放同一个工作单元;随后调用
AcceptAllChanges
才算完成保存。用于验证的 context 需要拥有自己的 execution strategy,因为刚刚失败的 connection 在检查时很可能再次失败。 3. 只有在最后,才使用普通的
CreateExecutionStrategy().ExecuteAsync
包装器,而且只能用于已经可以安全运行两次的工作单元。Delegate 不能捕获外部 context 所跟踪的 entity,不能依赖数据库生成的 key,也不能在其中发送 email、enqueue message 或 charge card。
有些工作单元无法实现幂等,此时只能选择承担重复写入风险或缩小 retry 范围,绝不能通过禁用 retry 来让异常消失。

What retry costs when it does not help

Retry 无效时付出的代价

UseAzureSql
defaults to 6 retries with a 30 second cap, so 7 attempts. The delays between them grow to roughly 0, 1, 3, 7.5, 15 and 30 seconds, so a permanently failing operation gives up only after close to a minute. A request thread is held for that whole minute, and behind a 30 second gateway timeout the caller has already given up. Size the retry budget against the deadline of the thing calling you, and put a
CancellationToken
through every async call.
UseAzureSql
默认执行 6 次 retry,最长等待时间为 30 秒,因此总共会尝试 7 次。各次尝试之间的延迟大约为 0、1、3、7.5、15 和 30 秒,所以持续失败的操作要等到接近一分钟后才会放弃。整个这段时间内,请求线程都会被占用;而在 30 秒的 gateway timeout 之后,调用方早已放弃请求。应根据调用方的 deadline 调整 retry budget,并在每次 async 调用中传递
CancellationToken
。

UseAzureSql, and the near miss

UseAzureSql
,以及容易误用的近似方案

From EF Core 9 there is a call named for this database, and Learn's own Azure SQL Database tab uses it. It does not delete
EnableRetryOnFailure
; it changes the default from off to on:
csharp
options.UseAzureSql(connectionString, o => o.UseCompatibilityLevel(170));
UseSqlServer
UseAzureSql
Engine type
SqlServer
AzureSql
Execution strategy
SqlServerExecutionStrategy
, no retry
SqlServerRetryingExecutionStrategy
, 6 retries, 30 second cap
Default compatibility level, EF Core 9150150
Default compatibility level, EF Core 10150170
Native
json
column type, EF Core 10
only at level 170 or aboveon by default
  • It is a compile time API. On EF Core 8 the call does not exist and the build says
    error CS1061: 'DbContextOptionsBuilder' does not contain a definition for 'UseAzureSql'
    . Upgrade the provider package rather than inventing an extension method.
  • When
    UseSqlServer
    is called by code you cannot change
    , EF Core 9 has a first party answer that is not obsolete, and it compiles clean:
    options.ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault());
    .
    UseSqlServer(cs, o => o.UseAzureSqlDefaults(true))
    also installs the retrying strategy, but it warns
    CS0618: 'UseAzureSqlDefaults(bool)' is obsolete
    and leaves the engine type as
    SqlServer
    , so the type mapping does not follow.
  • Retry numbers are defaults, not overrides. Supplying them alongside
    UseAzureSql
    replaces the 6 and the 30 seconds. Do that for a reason from your own workload, never by copying a blog post:
csharp
options.UseAzureSql(
    connectionString,
    o => o.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null));
Whether to retry at all is not a question on this database. The split is clean:
connect-to-azure-sql
owns retry at the driver and connection level, this skill owns the EF Core execution strategy above it and the transaction semantics that only exist up here.
从 EF Core 9 开始,provider 提供了一个以该数据库命名的调用方式,Microsoft Learn 自己的 Azure SQL Database 标签页也使用它。它不会删除
EnableRetryOnFailure
,而是将其默认值从关闭改为开启:
csharp
options.UseAzureSql(connectionString, o => o.UseCompatibilityLevel(170));
UseSqlServer
UseAzureSql
Engine type
SqlServer
AzureSql
Execution strategy
SqlServerExecutionStrategy
,不执行 retry
SqlServerRetryingExecutionStrategy
,执行 6 次 retry,最长等待 30 秒
EF Core 9 默认 compatibility level150150
EF Core 10 默认 compatibility level150170
EF Core 10 原生
json
column type
仅在 level 170 或更高时可用默认启用
  • **这是 compile-time API。**在 EF Core 8 中并不存在该调用,编译时会报告
    error CS1061: 'DbContextOptionsBuilder' does not contain a definition for 'UseAzureSql'
    。应升级 provider package,而不是自行编写 extension method。
  • 当
    UseSqlServer
    由无法修改的代码调用时
    ,EF Core 9 提供了非 obsolete 的一方支持方案,并且可以干净地编译:
    options.ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault());
    。
    UseSqlServer(cs, o => o.UseAzureSqlDefaults(true))
    同样会安装 retrying strategy,但它会产生
    CS0618: 'UseAzureSqlDefaults(bool)' is obsolete
    警告,并且仍将 engine type 保持为
    SqlServer
    ,因此 type mapping 不会随之切换。
  • **Retry 数值是默认值,而不是强制覆盖值。**在
    UseAzureSql
    中提供这些数值会替换默认的 6 次和 30 秒。应基于自身 workload 的明确原因进行设置,绝不能直接照搬博客文章:
csharp
options.UseAzureSql(
    connectionString,
    o => o.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null));
在这个数据库上,是否 retry 已不再是问题。职责划分非常明确:
connect-to-azure-sql
负责 driver 和 connection 级别的 retry,本 skill 负责其上层的 EF Core execution strategy,以及仅存在于该层的 transaction 语义。

Compatibility level, and the migration nobody expects

Compatibility level,以及无人预期的 migration

On EF Core 10,
UseAzureSql
defaults the compatibility level to 170, and at 170 the provider maps JSON to the native
json
column type instead of
nvarchar(max)
. Learn states it as a breaking change: upgrading an application that already uses
UseAzureSql
generates a migration that alters every existing
nvarchar(max)
JSON column to
json
: data movement on a live table, produced by a change that reads as configuration.
Generate the migration and read it before it reaches a database:
bash
dotnet ef migrations add UpgradeToEfCore10
dotnet ef migrations script --idempotent --output migrate.sql
grep -nE 'ALTER COLUMN|json' migrate.sql
Then choose, rather than inherit:
  • State the level. Learn names a level below 170 as the opt out, and its own example is
    o.UseCompatibilityLevel(160)
    , which keeps
    nvarchar(max)
    .
  • Pin one column with
    HasColumnType("nvarchar(max)")
    where only part of the model must wait.
  • Take the retype deliberately, in a window sized for the table, because the
    ALTER
    rewrites it.
The level does not gate
vector(n)
, which EF Core 10 surfaces as
SqlVector<float>
and
EF.Functions.VectorDistance
, so do not raise it expecting to unlock vectors. Storing embeddings is
vector-search-azure-sql
.
在 EF Core 10 中,
UseAzureSql
默认将 compatibility level 设为 170;达到 170 后,provider 会将 JSON 映射为原生
json
column type,而不是
nvarchar(max)
。Microsoft Learn 将其列为 breaking change:升级已经使用
UseAzureSql
的应用时,会生成 migration,将每个现有的
nvarchar(max)
JSON column 改为
json
。这会在生产表上移动数据,而引发变化的操作看起来仅仅是一项配置。
生成 migration,并在它到达数据库之前检查内容:
bash
dotnet ef migrations add UpgradeToEfCore10
dotnet ef migrations script --idempotent --output migrate.sql
grep -nE 'ALTER COLUMN|json' migrate.sql
随后应主动选择,而不是被动继承:
  • **明确指定 level。**Microsoft Learn 将低于 170 的 level 作为 opt-out,其示例为
    o.UseCompatibilityLevel(160)
    ,这会继续使用
    nvarchar(max)
    。
  • 如果只有部分 model 需要等待,则使用
    HasColumnType("nvarchar(max)")
    固定单个 column。
  • 如果确实需要转换类型,应有意识地执行,并为 table 预留足够大小的维护窗口,因为
    ALTER
    会重写该表。
该 level 不会控制
vector(n)
。EF Core 10 将其公开为
SqlVector<float>
和
EF.Functions.VectorDistance
,因此不要为了解锁 vector 而提高 level。存储 embeddings 属于
vector-search-azure-sql
的范畴。

Type mapping, honestly scoped

类型映射及其真实适用边界

Most EF Core type mapping advice applies to any engine this provider talks to and belongs to
design-azure-sql-schema
. Two things are different here.
DateTime
with
HasDefaultValueSql("GETDATE()")
.
Azure SQL Database offers no time zone choice:
CURRENT_TIMEZONE()
returns UTC and
GETDATE()
equals
SYSUTCDATETIME()
, in the local Azure SQL Database container and in the cloud alike. A model carried over from an engine running on local time changes meaning without changing shape. Prefer
DateTimeOffset
, or
SYSUTCDATETIME()
, and be explicit either way.
An indexed
string
with no
MaxLength
is narrowed to
nvarchar(450)
, and neither the index nor the data fails silently. From the script generated above, for one indexed string property:
text
[Name] nvarchar(450) NOT NULL,
CREATE INDEX [IX_Orders_Name] ON [Orders] ([Name]);
The
CREATE INDEX
succeeds and the engine then refuses anything longer, with
Msg 2628, String or binary data would be truncated in table '<table>', column '<column>'
. Adding the index later to a column already holding longer values fails the same way on the
ALTER COLUMN
, so the migration stops rather than trimming data. Set
HasMaxLength
deliberately instead of discovering the 450 at deployment.
大多数 EF Core type mapping 建议都适用于该 provider 支持的任何 engine,应归入
design-azure-sql-schema
。这里有两点有所不同。
**使用
HasDefaultValueSql("GETDATE()")
的
DateTime
。**Azure SQL Database 不提供 time zone 选择:
CURRENT_TIMEZONE()
返回 UTC,
GETDATE()
等同于
SYSUTCDATETIME()
;无论是在本地 Azure SQL Database container 中还是在 cloud 中,这一点都成立。从按本地时间运行的 engine 迁移过来的 model,即使结构没有变化,其含义也会发生改变。应优先使用
DateTimeOffset
,或者使用
SYSUTCDATETIME()
,无论采用哪种方式都应明确说明。
未设置
MaxLength
的 indexed
string
会被收窄为
nvarchar(450)
,而且 index 和数据都不会静默失败。根据上面生成的 script,对于一个 indexed string property:
text
[Name] nvarchar(450) NOT NULL,
CREATE INDEX [IX_Orders_Name] ON [Orders] ([Name]);
CREATE INDEX
会成功执行,随后 engine 会拒绝任何更长的值,并报告
Msg 2628, String or binary data would be truncated in table '<table>', column '<column>'
。如果 column 中已经存在较长的值,之后再添加 index,也会在
ALTER COLUMN
处以相同方式失败,因此 migration 会停止,而不会静默截断数据。应主动设置
HasMaxLength
,而不是等到部署时才发现 450 的限制。

Single and split queries over a wide area network

广域网络中的 single query 与 split query

Include
of two sibling collections produces a cross product. That is engine independent. What changes here is the arithmetic of the fix, because each extra query is a real network round trip.
  • Prefer split when the cartesian product is large: moving duplicated megabytes costs more.
  • Prefer single for small collections and chatty request paths.
  • Measure. The break even point moves with row width and with distance.
  • Split queries are not one consistent read unless wrapped in a snapshot or serializable transaction, which puts them back under everything above.
Slow query triage is
slow-query-investigation
.
对两个 sibling collection 执行
Include
会产生 cartesian product。这与 engine 无关。这里发生变化的是修复方案的计算方式,因为每一个额外 query 都意味着一次真实的 network round trip。
  • 当 cartesian product 很大时,优先使用 split query:传输重复的数 MB 数据成本更高。
  • 对于较小的 collection 以及包含大量 query 的 request path,优先使用 single query。
  • 进行测量。盈亏平衡点会随 row width 和网络距离而变化。
  • Split query 并不属于同一次一致性读取,除非将其包装在 snapshot 或 serializable transaction 中;这样又会使其受到上述所有约束。
Slow query 的分诊方法参见
slow-query-investigation
。

Migrations against a cloud database

面向 cloud 数据库的 migration

Doctrine and deployment sequencing are
schema-migrations-safely
; the declarative alternative is
sql-database-projects
. Only the Azure SQL Database parts are here:
bash
dotnet ef database update \
  --connection "Server=tcp:your-server.database.windows.net,1433;Database=your-database;Authentication=Active Directory Default;Encrypt=Mandatory;"
  • It runs from wherever it is invoked, so that machine needs a server firewall rule for its own address and a principal that can change the schema. Neither is the application's runtime identity, and
    --connection
    is how the two are kept apart: it overrides the string in
    AddDbContext
    or
    OnConfiguring
    without editing the application.
  • The database itself is not created by a migration. That is
    provision-azure-sql-db
    .
  • Do not migrate from application startup here. EF Core 9 added a database wide lock, so the concurrency objection you may recall is out of date. The objection that survives is permissions: startup migration means the runtime identity holds schema rights permanently.
Migration 原则和部署顺序参见
schema-migrations-safely
;声明式替代方案是
sql-database-projects
。这里仅介绍 Azure SQL Database 相关的部分:
bash
dotnet ef database update \
  --connection "Server=tcp:your-server.database.windows.net,1433;Database=your-database;Authentication=Active Directory Default;Encrypt=Mandatory;"
  • Migration 会在执行命令所在的位置运行,因此该机器需要一条允许自身地址的 server firewall rule,还需要一个能够修改 schema 的 principal。这两者都不是应用的 runtime identity,而
    --connection
    正是将二者区分开的方式:它会覆盖
    AddDbContext
    或
    OnConfiguring
    中的 connection string,无需修改应用代码。
  • **Migration 本身不会创建数据库。**创建数据库应使用
    provision-azure-sql-db
    。
  • **不要在这里从 application startup 执行 migration。**EF Core 9 添加了 database-wide lock,因此你可能记得的并发迁移反对意见已经过时。仍然成立的问题是权限:从 startup 执行 migration 意味着 runtime identity 会永久持有 schema 权限。

Connecting with an identity rather than a password

使用 identity 而非密码连接

Nothing in the
DbContext
changes.
UseAzureSql
takes the same connection string a bare driver would, so passwordless access stays a connection string concern:
text
Server=tcp:your-server.database.windows.net,1433;Database=your-database;Authentication=Active Directory Default;Encrypt=Mandatory;
Getting an identity to a working connection is
entra-id-auth
. Packages, authentication modes and pooling are
connect-from-dotnet
.
DbContext
不需要做任何更改。
UseAzureSql
接受与裸 driver 相同的 connection string,因此 passwordless access 仍然属于 connection string 的问题:
text
Server=tcp:your-server.database.windows.net,1433;Database=your-database;Authentication=Active Directory Default;Encrypt=Mandatory;
如何让 identity 建立可用连接由
entra-id-auth
负责。Package、authentication mode 和 pooling 则由
connect-from-dotnet
负责。

Check it worked

检查是否生效

Three checks, in the order they catch things.
The context is on the Azure SQL Database path at all. Nothing in the connection string says so, and this is the only command that prints it:
bash
dotnet ef dbcontext info
Expect
Options: EngineType=AzureSql
. Under
UseSqlServer
, with or without a hand written
EnableRetryOnFailure
, the same line reads
Options: EngineType=SqlServer
, which is how a
UseAzureSqlDefaults
configuration is caught: it retries, and it still prints
SqlServer
.
The model and the migrations agree, before a deployment discovers they do not:
bash
dotnet ef migrations has-pending-model-changes
Expect exit code 0 and
No changes have been made to the model since the last migration.
Exit code 1 and
Changes have been made to the model since the last migration.
is the failure, and it is the one that becomes an unexplained
ALTER
in somebody else's release.
A replayed unit collides instead of duplicating. An idempotency key is only a defence if the index over it is unique:
sql
SELECT i.name, i.is_unique
FROM sys.indexes AS i
WHERE i.object_id = OBJECT_ID('dbo.Orders') AND i.is_unique = 1;
Expect one row, the index over the key column. With
is_unique
1 a replayed insert fails with
Msg 2601, Cannot insert duplicate key row in object 'dbo.Orders' with unique index
; with a non-unique index the replay writes a second row and the whole defence is decorative.
共进行三项检查,按照它们发现问题的顺序排列。
**首先确认 context 确实运行在 Azure SQL Database 路径上。**Connection string 中没有任何内容能够表明这一点,而下面这个命令是唯一会打印该信息的命令:
bash
dotnet ef dbcontext info
预期输出为
Options: EngineType=AzureSql
。在
UseSqlServer
下,无论是否手工配置了
EnableRetryOnFailure
,同一行都会显示
Options: EngineType=SqlServer
。这正是发现
UseAzureSqlDefaults
配置问题的方式:它会执行 retry,却仍然打印
SqlServer
。
其次确认 model 和 migration 保持一致,不要等到部署时才发现不一致:
bash
dotnet ef migrations has-pending-model-changes
预期退出码为 0,并输出
No changes have been made to the model since the last migration.
。退出码为 1,并输出
Changes have been made to the model since the last migration.
,表示检查失败;如果放任不管,它就会变成其他人 release 中一个无法解释的
ALTER
。
**最后确认重放工作单元时会发生冲突,而不是产生重复数据。**只有当 idempotency key 上存在 unique index 时,它才能发挥防护作用:
sql
SELECT i.name, i.is_unique
FROM sys.indexes AS i
WHERE i.object_id = OBJECT_ID('dbo.Orders') AND i.is_unique = 1;
预期返回一行,即 key column 上的 index。当
is_unique
为 1 时,重放 insert 会因
Msg 2601, Cannot insert duplicate key row in object 'dbo.Orders' with unique index
而失败;如果使用 non-unique index,重放会写入第二行,整个防护就只是表面功夫。

Do not

禁止事项

  • Do not treat the execution strategy exception as the end of the work. It is the visible half, and the silent half is a duplicate write.
  • Do not put a hand written
    BeginTransaction
    and
    Commit
    inside a retried delegate without an idempotency key or a
    verifySucceeded
    predicate. It compiles, it passes review, and it doubles a row on the fault it was configured to expect.
  • Do not drop
    acceptAllChangesOnSuccess: false
    from the
    ExecuteInTransaction
    form. Without it the entity is marked
    Unchanged
    and the replay saves nothing.
  • Do not assume
    Database.BeginTransaction
    throws. It succeeds, and the next query or
    SaveChanges
    throws. Raw SQL inside that transaction is not guarded at all.
  • Do not disable retry to make a transaction error disappear, and do not leave the retry budget larger than the caller's timeout.
  • Do not claim
    UseAzureSql
    removes
    EnableRetryOnFailure
    . It sets its default.
  • Do not reach for
    UseAzureSqlDefaults(true)
    . It is obsolete, and it leaves the engine type unchanged;
    ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault())
    is the supported form.
  • Do not upgrade to EF Core 10 and switch to
    UseAzureSql
    in the same change without reading the next migration.
  • Do not add
    AsSplitQuery
    everywhere by reflex. Over a network it can cost more than it saves.
  • Do not apply migrations from application startup against a cloud database.
  • Do not leave an indexed string property without
    HasMaxLength
    , and do not leave two sibling collection
    Include
    calls without
    AsSplitQuery
    or
    AsSingleQuery
    .
  • Do not give the application's runtime identity schema permission, and do not put a connection string, password or server hostname in source.
  • Do not use this skill for a different object relational mapper, or for raw
    Microsoft.Data.SqlClient
    work.
  • 不要将 execution strategy 异常视为问题的终点。它只是看得见的部分,看不见的部分是重复写入。
  • 不要在没有 idempotency key 或
    verifySucceeded
    predicate 的情况下,把手工编写的
    BeginTransaction
    和
    Commit
    放入被 retry 的 delegate 中。它能够编译,也能通过 review,却会在预期发生的故障上把一行数据写入两次。
  • 不要从
    ExecuteInTransaction
    形式中删除
    acceptAllChangesOnSuccess: false
    。否则 entity 会被标记为
    Unchanged
    ,重放时将不会保存任何内容。
  • 不要假设
    Database.BeginTransaction
    会抛出异常。它会成功执行,随后执行 query 或
    SaveChanges
    时才会抛出异常。该 transaction 中的原始 SQL 完全不会受到保护。
  • 不要为了消除 transaction 错误而禁用 retry,也不要让 retry budget 大于调用方的 timeout。
  • 不要声称
    UseAzureSql
    会移除
    EnableRetryOnFailure
    。它只会设置默认值。
  • 不要使用
    UseAzureSqlDefaults(true)
    。它已经 obsolete,并且不会改变 engine type;受支持的写法是
    ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault())
    。
  • 不要在同一次变更中升级到 EF Core 10 并切换到
    UseAzureSql
    ,除非已经检查过下一项 migration。
  • 不要出于习惯到处添加
    AsSplitQuery
    。在 network 环境中,它的成本可能高于收益。
  • 不要针对 cloud database 从 application startup 执行 migration。
  • 不要让 indexed string property 缺少
    HasMaxLength
    ,也不要让包含两个 sibling collection 的
    Include
    在未指定
    AsSplitQuery
    或
    AsSingleQuery
    的情况下运行。
  • 不要向应用的 runtime identity授予 schema 权限,也不要把 connection string、password 或 server hostname 放入源代码。
  • 不要将本 skill 用于其他 object relational mapper,也不要用于直接处理
    Microsoft.Data.SqlClient
    的工作。

References

参考

  • Checks behind the tables above, with the setup to run them
  • Connection resiliency: execution strategies, the transaction rule, and the four documented answers to a commit that fails with an unknown outcome. Read it before writing anything transactional.
  • Microsoft SQL Server database provider: the first party statement of
    UseAzureSql
    ,
    UseCompatibilityLevel
    and
    ConfigureSqlEngine
    .
  • Breaking changes in EF Core 10: read before an EF Core 10 upgrade, for the JSON retype and the compatibility level that gates it.
  • Single vs split queries: cartesian explosion and every characteristic of split queries.
  • Underneath this skill:
    connect-to-azure-sql
    for retry and pool sizing at the connection level,
    connect-from-dotnet
    for the driver and packages,
    entra-id-auth
    for a passwordless identity.
  • Beside it:
    design-azure-sql-schema
    for string sizing and collation, and
    schema-migrations-safely
    for how migrations reach a database.
  • 上述表格背后的检查及运行设置
  • Connection resiliency:介绍 execution strategy、transaction 规则,以及针对结果未知且失败的 commit 的四种官方处理方式。在编写任何 transaction 代码之前应先阅读。
  • Microsoft SQL Server database provider:关于
    UseAzureSql
    、
    UseCompatibilityLevel
    和
    ConfigureSqlEngine
    的一方说明。
  • Breaking changes in EF Core 10:升级到 EF Core 10 前阅读,了解 JSON 类型转换以及控制该转换的 compatibility level。
  • Single vs split queries:介绍 cartesian explosion 以及 split query 的所有重要特征。
  • 本 skill 下方:
    connect-to-azure-sql
    负责连接级别的 retry 和 pool sizing,
    connect-from-dotnet
    负责 driver 和 package,
    entra-id-auth
    负责 passwordless identity。
  • 与本 skill 并列:
    design-azure-sql-schema
    负责 string sizing 和 collation,
    schema-migrations-safely
    负责 migration 如何到达数据库。