SetExecutionStrategy to SqlAzureExecutionStrategy with DbMigrationsConfiguration?

ⅰ亾dé卋堺 提交于 2019-12-04 23:07:23

If anyone else comes across this question, this is what we figured out:

Create a custom class that inherits from DbConfiguration (which has SetExecutionStrategy):

public class DataContextConfiguration : DbConfiguration
{
    public DataContextConfiguration()
    {
        SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
    }
}

Then add this attribute to your DataContext, specifying that it is to use your custom class:

[DbConfigurationType(typeof(DataContextConfiguration))]
public class DataContext : DbContext, IDataContext
{
    ...
}

After more investigation, now I think the correct answer is that: DbMigrationsConfiguration is completely separate and only configures the migration settings. That's why it doesn't inherit from or have the same options as DbConfiguration.

It is not loaded, and is irrelevant, for actual operation.

So you can (and should) declare a separate class based on DbConfiguration to configure the runtime behaviour.

I added some tracing and I saw that the first time you use a DatabaseContext in an application, it runs up the migration, and the migration configuration. But, the first time the DatabaseContext is actually used (e.g. to load some data from the database) it will load your DbConfiguration class as well.

So I don't think there is any problem at all.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!