ef-core-azure-sql
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseEF 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 work the same everywhere and are not repeated here.
IncludeCommand output, compiler results and runtime behaviour below are for
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.
Microsoft.EntityFrameworkCore.SqlServer本文介绍 EF Core 在 Azure SQL Database 基础上的差异部分,而不是 EF Core 教程。建模、LINQ、change tracking 和 在各处的工作方式都相同,因此不再重复。
Include除非某一行另有说明,下文的命令输出、编译器结果和运行时行为均基于 9。EF Core 10 是受支持的长期发布版本,EF Core 9 仍处于维护阶段。
如果下述内容与实际观察不符,或想自行运行检查,请打开 references/retry-transactions-and-type-mapping.md。
Microsoft.EntityFrameworkCore.SqlServerScope
范围
- The Azure SQL Database delta on EF Core, not general EF Core.
- Pooling is , retry doctrine
connect-from-dotnet, identityconnect-to-azure-sql, and running migrations from a pipelineentra-id-auth.github-actions-for-sql
- EF Core 相对通用实现的 Azure SQL Database 差异,而不是通用 EF Core 内容。
- 连接池由 处理,retry 原则由
connect-from-dotnet处理,identity 由connect-to-azure-sql处理,从 pipeline 运行 migration 则由entra-id-auth处理。github-actions-for-sql
The correction
核心修正
Retry is not a setting on this database. Every current recommendation turns it on:
in older code, in newer code. Both produce
, 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:
EnableRetryOnFailureUseAzureSqlSqlServerRetryingExecutionStrategycsharp
// 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 并非一项可选设置。当前所有推荐做法都会启用它:旧代码使用 ,新代码使用 。两者都会创建 ,并且启用它会悄无声息地重新定义 transaction 的含义。看得见的部分是一个异常,但异常本身并不是问题。真正的问题在于异常之后编写的代码,因为异常已经决定了相应的补救方式,而这种补救并不完整:
EnableRetryOnFailureUseAzureSqlSqlServerRetryingExecutionStrategycsharp
// 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 throws, is wrong.
Database.BeginTransaction| Call, with the retrying strategy configured | Result |
|---|---|
| Succeeds. No exception |
| A LINQ query while that transaction is open | Throws |
| Throws |
| Succeeds. Not guarded at all |
| 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 | 结果 |
|---|---|
单独调用 | **成功。**不会抛出异常 |
| transaction 打开期间执行 LINQ query | 立即抛出 |
transaction 打开期间执行 | 立即抛出 |
transaction 打开期间执行 | **成功。**完全没有受到保护 |
未使用显式 transaction 时执行 | 成功。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 arrives | Delegate runs | Rows committed | What the caller sees |
|---|---|---|---|
Before | 2 | 1 | Success. Correct, the first attempt rolled back |
After | 2 | 2 | Success. 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 执行次数 | 已提交行数 | 调用方看到的结果 |
|---|---|---|---|
| 2 | 1 | 成功。第一次尝试已回滚,结果正确 |
| 2 | 2 | 成功。没有异常、没有警告,也没有日志 |
风险窗口就在 commit acknowledgement 环节:提交已经到达服务器,但确认没有到达客户端,而策略无法将其与从未发生的提交区分开来,因此会重放一个实际上已经成功的工作单元。Microsoft Learn 将此称为 idempotency 问题,并指出它可能导致 data corruption。其影响范围是 transaction 路径上的静默双写,只会在生产环境中发生,并且恰好发生在该数据库被配置为预期发生的瞬时故障上。
Making the unit safe to run twice
让工作单元可以安全运行两次
In order of preference.
- Give the write a natural idempotency key and a unique index, so a replay collides with
instead of duplicating. This is the only defence that survives a process crash between the two attempts.
Msg 2601 - Hand the transaction to with a
ExecuteInTransactionpredicate. The strategy owns the transaction and, when the commit fails with an unknown outcome, asks the predicate whether the work already landed before retrying:verifySucceeded
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: falseAddedAcceptAllChanges- Only then the bare 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.
CreateExecutionStrategy().ExecuteAsync
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.
按优先级排列。
- 为写入提供天然的 idempotency key 和 unique index,这样重放时就会与 冲突,而不是产生重复数据。这是唯一能够在两次尝试之间发生进程崩溃时仍然有效的防护。
Msg 2601 - **将 transaction 交给 ,并提供
ExecuteInTransactionpredicate。**由策略管理 transaction;当 commit 以结果未知的方式失败时,策略会在 retry 前询问 predicate,以判断工作是否已经落库:verifySucceeded
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: falseAddedAcceptAllChangesCreateExecutionStrategy().ExecuteAsync有些工作单元无法实现幂等,此时只能选择承担重复写入风险或缩小 retry 范围,绝不能通过禁用 retry 来让异常消失。
What retry costs when it does not help
Retry 无效时付出的代价
UseAzureSqlCancellationTokenUseAzureSqlCancellationTokenUseAzureSql, and the near miss
UseAzureSql
,以及容易误用的近似方案
UseAzureSqlFrom 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 ; it changes the default from off to on:
EnableRetryOnFailurecsharp
options.UseAzureSql(connectionString, o => o.UseCompatibilityLevel(170)); | | |
|---|---|---|
| Engine type | | |
| Execution strategy | | |
| Default compatibility level, EF Core 9 | 150 | 150 |
| Default compatibility level, EF Core 10 | 150 | 170 |
Native | only at level 170 or above | on by default |
- It is a compile time API. On EF Core 8 the call does not exist and the build says
. Upgrade the provider package rather than inventing an extension method.
error CS1061: 'DbContextOptionsBuilder' does not contain a definition for 'UseAzureSql' - When is called by code you cannot change, EF Core 9 has a first party answer that is not obsolete, and it compiles clean:
UseSqlServer.options.ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault());also installs the retrying strategy, but it warnsUseSqlServer(cs, o => o.UseAzureSqlDefaults(true))and leaves the engine type asCS0618: 'UseAzureSqlDefaults(bool)' is obsolete, so the type mapping does not follow.SqlServer - Retry numbers are defaults, not overrides. Supplying them alongside replaces the 6 and the 30 seconds. Do that for a reason from your own workload, never by copying a blog post:
UseAzureSql
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:
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.
connect-to-azure-sql从 EF Core 9 开始,provider 提供了一个以该数据库命名的调用方式,Microsoft Learn 自己的 Azure SQL Database 标签页也使用它。它不会删除 ,而是将其默认值从关闭改为开启:
EnableRetryOnFailurecsharp
options.UseAzureSql(connectionString, o => o.UseCompatibilityLevel(170)); | | |
|---|---|---|
| Engine type | | |
| Execution strategy | | |
| EF Core 9 默认 compatibility level | 150 | 150 |
| EF Core 10 默认 compatibility level | 150 | 170 |
EF Core 10 原生 | 仅在 level 170 或更高时可用 | 默认启用 |
- **这是 compile-time API。**在 EF Core 8 中并不存在该调用,编译时会报告 。应升级 provider package,而不是自行编写 extension method。
error CS1061: 'DbContextOptionsBuilder' does not contain a definition for 'UseAzureSql' - 当 由无法修改的代码调用时,EF Core 9 提供了非 obsolete 的一方支持方案,并且可以干净地编译:
UseSqlServer。options.ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault());同样会安装 retrying strategy,但它会产生UseSqlServer(cs, o => o.UseAzureSqlDefaults(true))警告,并且仍将 engine type 保持为CS0618: 'UseAzureSqlDefaults(bool)' is obsolete,因此 type mapping 不会随之切换。SqlServer - **Retry 数值是默认值,而不是强制覆盖值。**在 中提供这些数值会替换默认的 6 次和 30 秒。应基于自身 workload 的明确原因进行设置,绝不能直接照搬博客文章:
UseAzureSql
csharp
options.UseAzureSql(
connectionString,
o => o.EnableRetryOnFailure(maxRetryCount: 3, maxRetryDelay: TimeSpan.FromSeconds(10), errorNumbersToAdd: null));在这个数据库上,是否 retry 已不再是问题。职责划分非常明确:
负责 driver 和 connection 级别的 retry,本 skill 负责其上层的 EF Core execution strategy,以及仅存在于该层的 transaction 语义。
connect-to-azure-sqlCompatibility level, and the migration nobody expects
Compatibility level,以及无人预期的 migration
On EF Core 10, defaults the compatibility level to 170, and at 170 the provider
maps JSON to the native column type instead of . Learn states it as a
breaking change: upgrading an application that already uses generates a migration that
alters every existing JSON column to : data movement on a live table,
produced by a change that reads as configuration.
UseAzureSqljsonnvarchar(max)UseAzureSqlnvarchar(max)jsonGenerate 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.sqlThen choose, rather than inherit:
- State the level. Learn names a level below 170 as the opt out, and its own example is
, which keeps
o.UseCompatibilityLevel(160).nvarchar(max) - Pin one column with where only part of the model must wait.
HasColumnType("nvarchar(max)") - Take the retype deliberately, in a window sized for the table, because the rewrites it.
ALTER
The level does not gate , which EF Core 10 surfaces as and
, so do not raise it expecting to unlock vectors. Storing embeddings is
.
vector(n)SqlVector<float>EF.Functions.VectorDistancevector-search-azure-sql在 EF Core 10 中, 默认将 compatibility level 设为 170;达到 170 后,provider 会将 JSON 映射为原生 column type,而不是 。Microsoft Learn 将其列为 breaking change:升级已经使用 的应用时,会生成 migration,将每个现有的 JSON column 改为 。这会在生产表上移动数据,而引发变化的操作看起来仅仅是一项配置。
UseAzureSqljsonnvarchar(max)UseAzureSqlnvarchar(max)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 需要等待,则使用 固定单个 column。
HasColumnType("nvarchar(max)") - 如果确实需要转换类型,应有意识地执行,并为 table 预留足够大小的维护窗口,因为 会重写该表。
ALTER
该 level 不会控制 。EF Core 10 将其公开为 和 ,因此不要为了解锁 vector 而提高 level。存储 embeddings 属于 的范畴。
vector(n)SqlVector<float>EF.Functions.VectorDistancevector-search-azure-sqlType mapping, honestly scoped
类型映射及其真实适用边界
Most EF Core type mapping advice applies to any engine this provider talks to and belongs to
. Two things are different here.
design-azure-sql-schemaDateTimeHasDefaultValueSql("GETDATE()")CURRENT_TIMEZONE()GETDATE()SYSUTCDATETIME()DateTimeOffsetSYSUTCDATETIME()An indexed with no is narrowed to , and neither the index
nor the data fails silently. From the script generated above, for one indexed string property:
stringMaxLengthnvarchar(450)text
[Name] nvarchar(450) NOT NULL,
CREATE INDEX [IX_Orders_Name] ON [Orders] ([Name]);The succeeds and the engine then refuses anything longer, with
. Adding
the index later to a column already holding longer values fails the same way on the ,
so the migration stops rather than trimming data. Set deliberately instead of
discovering the 450 at deployment.
CREATE INDEXMsg 2628, String or binary data would be truncated in table '<table>', column '<column>'ALTER COLUMNHasMaxLength大多数 EF Core type mapping 建议都适用于该 provider 支持的任何 engine,应归入 。这里有两点有所不同。
design-azure-sql-schema**使用 的 。**Azure SQL Database 不提供 time zone 选择: 返回 UTC, 等同于 ;无论是在本地 Azure SQL Database container 中还是在 cloud 中,这一点都成立。从按本地时间运行的 engine 迁移过来的 model,即使结构没有变化,其含义也会发生改变。应优先使用 ,或者使用 ,无论采用哪种方式都应明确说明。
HasDefaultValueSql("GETDATE()")DateTimeCURRENT_TIMEZONE()GETDATE()SYSUTCDATETIME()DateTimeOffsetSYSUTCDATETIME()未设置 的 indexed 会被收窄为 ,而且 index 和数据都不会静默失败。根据上面生成的 script,对于一个 indexed string property:
MaxLengthstringnvarchar(450)text
[Name] nvarchar(450) NOT NULL,
CREATE INDEX [IX_Orders_Name] ON [Orders] ([Name]);CREATE INDEXMsg 2628, String or binary data would be truncated in table '<table>', column '<column>'ALTER COLUMNHasMaxLengthSingle and split queries over a wide area network
广域网络中的 single query 与 split query
Include- 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 执行 会产生 cartesian product。这与 engine 无关。这里发生变化的是修复方案的计算方式,因为每一个额外 query 都意味着一次真实的 network round trip。
Include- 当 cartesian product 很大时,优先使用 split query:传输重复的数 MB 数据成本更高。
- 对于较小的 collection 以及包含大量 query 的 request path,优先使用 single query。
- 进行测量。盈亏平衡点会随 row width 和网络距离而变化。
- Split query 并不属于同一次一致性读取,除非将其包装在 snapshot 或 serializable transaction 中;这样又会使其受到上述所有约束。
Slow query 的分诊方法参见 。
slow-query-investigationMigrations against a cloud database
面向 cloud 数据库的 migration
Doctrine and deployment sequencing are ; the declarative alternative is
. Only the Azure SQL Database parts are here:
schema-migrations-safelysql-database-projectsbash
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 is how the two are kept apart: it overrides the string in
--connectionorAddDbContextwithout editing the application.OnConfiguring - 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 原则和部署顺序参见 ;声明式替代方案是 。这里仅介绍 Azure SQL Database 相关的部分:
schema-migrations-safelysql-database-projectsbash
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中的 connection string,无需修改应用代码。OnConfiguring - **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 changes. takes the same connection string a bare driver
would, so passwordless access stays a connection string concern:
DbContextUseAzureSqltext
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 . Packages, authentication modes and
pooling are .
entra-id-authconnect-from-dotnetDbContextUseAzureSqltext
Server=tcp:your-server.database.windows.net,1433;Database=your-database;Authentication=Active Directory Default;Encrypt=Mandatory;如何让 identity 建立可用连接由 负责。Package、authentication mode 和 pooling 则由 负责。
entra-id-authconnect-from-dotnetCheck 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 infoExpect . Under , with or without a hand written
, the same line reads , which is how a
configuration is caught: it retries, and it still prints .
Options: EngineType=AzureSqlUseSqlServerEnableRetryOnFailureOptions: EngineType=SqlServerUseAzureSqlDefaultsSqlServerThe model and the migrations agree, before a deployment discovers they do not:
bash
dotnet ef migrations has-pending-model-changesExpect exit code 0 and Exit code
1 and is the failure, and it is the
one that becomes an unexplained in somebody else's release.
No changes have been made to the model since the last migration.Changes have been made to the model since the last migration.ALTERA 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 1 a replayed insert fails with
; with a
non-unique index the replay writes a second row and the whole defence is decorative.
is_uniqueMsg 2601, Cannot insert duplicate key row in object 'dbo.Orders' with unique index共进行三项检查,按照它们发现问题的顺序排列。
**首先确认 context 确实运行在 Azure SQL Database 路径上。**Connection string 中没有任何内容能够表明这一点,而下面这个命令是唯一会打印该信息的命令:
bash
dotnet ef dbcontext info预期输出为 。在 下,无论是否手工配置了 ,同一行都会显示 。这正是发现 配置问题的方式:它会执行 retry,却仍然打印 。
Options: EngineType=AzureSqlUseSqlServerEnableRetryOnFailureOptions: EngineType=SqlServerUseAzureSqlDefaultsSqlServer其次确认 model 和 migration 保持一致,不要等到部署时才发现不一致:
bash
dotnet ef migrations has-pending-model-changes预期退出码为 0,并输出 。退出码为 1,并输出 ,表示检查失败;如果放任不管,它就会变成其他人 release 中一个无法解释的 。
No changes have been made to the model since the last migration.Changes have been made to the model since the last migration.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。当 为 1 时,重放 insert 会因 而失败;如果使用 non-unique index,重放会写入第二行,整个防护就只是表面功夫。
is_uniqueMsg 2601, Cannot insert duplicate key row in object 'dbo.Orders' with unique indexDo 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 and
BeginTransactioninside a retried delegate without an idempotency key or aCommitpredicate. It compiles, it passes review, and it doubles a row on the fault it was configured to expect.verifySucceeded - Do not drop from the
acceptAllChangesOnSuccess: falseform. Without it the entity is markedExecuteInTransactionand the replay saves nothing.Unchanged - Do not assume throws. It succeeds, and the next query or
Database.BeginTransactionthrows. Raw SQL inside that transaction is not guarded at all.SaveChanges - 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 removes
UseAzureSql. It sets its default.EnableRetryOnFailure - Do not reach for . It is obsolete, and it leaves the engine type unchanged;
UseAzureSqlDefaults(true)is the supported form.ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault()) - Do not upgrade to EF Core 10 and switch to in the same change without reading the next migration.
UseAzureSql - Do not add everywhere by reflex. Over a network it can cost more than it saves.
AsSplitQuery - Do not apply migrations from application startup against a cloud database.
- Do not leave an indexed string property without , and do not leave two sibling collection
HasMaxLengthcalls withoutIncludeorAsSplitQuery.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
work.
Microsoft.Data.SqlClient
- 不要将 execution strategy 异常视为问题的终点。它只是看得见的部分,看不见的部分是重复写入。
- 不要在没有 idempotency key 或 predicate 的情况下,把手工编写的
verifySucceeded和BeginTransaction放入被 retry 的 delegate 中。它能够编译,也能通过 review,却会在预期发生的故障上把一行数据写入两次。Commit - 不要从 形式中删除
ExecuteInTransaction。否则 entity 会被标记为acceptAllChangesOnSuccess: false,重放时将不会保存任何内容。Unchanged - 不要假设 会抛出异常。它会成功执行,随后执行 query 或
Database.BeginTransaction时才会抛出异常。该 transaction 中的原始 SQL 完全不会受到保护。SaveChanges - 不要为了消除 transaction 错误而禁用 retry,也不要让 retry budget 大于调用方的 timeout。
- 不要声称 会移除
UseAzureSql。它只会设置默认值。EnableRetryOnFailure - 不要使用 。它已经 obsolete,并且不会改变 engine type;受支持的写法是
UseAzureSqlDefaults(true)。ConfigureSqlEngine(c => c.EnableRetryOnFailureByDefault()) - 不要在同一次变更中升级到 EF Core 10 并切换到 ,除非已经检查过下一项 migration。
UseAzureSql - 不要出于习惯到处添加 。在 network 环境中,它的成本可能高于收益。
AsSplitQuery - 不要针对 cloud database 从 application startup 执行 migration。
- 不要让 indexed string property 缺少 ,也不要让包含两个 sibling collection 的
HasMaxLength在未指定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 ,
UseAzureSqlandUseCompatibilityLevel.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: for retry and pool sizing at the connection level,
connect-to-azure-sqlfor the driver and packages,connect-from-dotnetfor a passwordless identity.entra-id-auth - Beside it: for string sizing and collation, and
design-azure-sql-schemafor how migrations reach a database.schema-migrations-safely
- 上述表格背后的检查及运行设置
- 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 下方:负责连接级别的 retry 和 pool sizing,
connect-to-azure-sql负责 driver 和 package,connect-from-dotnet负责 passwordless identity。entra-id-auth - 与本 skill 并列:负责 string sizing 和 collation,
design-azure-sql-schema负责 migration 如何到达数据库。schema-migrations-safely