gpt4 book ai didi

sql-server - 我们如何在 Entity Framework Core 中测试连接弹性

转载 作者:行者123 更新时间:2023-12-04 15:45:55 25 4
gpt4 key购买 nike

我在 Entity Framework Core 中打开了连接弹性:

services.AddDbContext<MyDbContext>( options =>
options.UseSqlServer(Configurations["ConnectionString"]),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure(
maxRetryCount: 10,
maxRetryDelay: TimeSpan.FromSeconds(5),
errorNumbersToAdd: null);
});

现在我想创建一些单元测试来证明这确实有效。
有可能做这样的事情吗?
InMemoryDbContext似乎没有 EnableRetryOnFailure方法和我能找到的最相似的测试是在 EF6 中:
https://thedatafarm.com/data-access/testing-out-the-connection-resiliency-feature-into-ef6/

(这有点复杂)

作为一些附加信息,我正在使用 SQL Server 2017 和 Entity Framework Core 2.2.0,在手动测试时,如果我使数据库脱机,它会立即失败。

我是测试错误还是缺少正确设置的东西?

最佳答案

Jeroen Mostert 在评论中回答了这个问题:

If by "taking the database offline" you literally mean setting thedatabase state to OFFLINE, the failure is expected -- that's not oneof the conditions resiliency guards against, as it is not a transientcondition that would most likely resolve itself in time. If the serveris up but the database was explicitly set offline, you'll immediatelyget that back as an error -- adding retry for that, if desired, is upto your application. To test connection resiliency, you have to takedown the server itself -- i.e. shut down SQL Server (or firewall port1433, same effect).

Incidentallly, the errorNumbersToAdd property should allow you to mark"database is offline" as a transient error, if so desired -- the errornumber is 942. Use this only if it makes sense in production as well-- otherwise, for testing, it makes more sense to add 50000, the error number of a custom RAISERROR (e.g. RAISERROR('This is a transienterror!', 11, 0)), which is easy to inject in queries. Don't use thatin production either, of course, since most custom errors should notbe blindly retried -- it makes more sense to use something like Pollyfor that.


这似乎是最好的解释。

关于sql-server - 我们如何在 Entity Framework Core 中测试连接弹性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com