3 回答

TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超18個(gè)贊
在微軟的幫助下,我終于弄清楚了。希望這對(duì)其他人有幫助。我必須創(chuàng)建自己的類繼承自 DbConfiguration
public class MyCustomSQLDbConfiguration : DbConfiguration
{
public MyCustomSQLDbConfiguration()
{
SetExecutionStrategy("MySql.Data.MySqlClient", () => new MySqlExecutionStrategy());
SetDefaultConnectionFactory(new LocalDbConnectionFactory("mssqllocaldb"));
}
}
然后相應(yīng)地裝飾我的 MySqlDBContext:
[DbConfigurationType(typeof(MyCustomSQLDbConfiguration))]
public class MySqlDBContext : DbContext
{
public MySqlDBContext() : base("MySqlDBContext")
{
}
}
最后(也是重要的),在運(yùn)行應(yīng)用程序時(shí)顯式設(shè)置它。對(duì)于控制臺(tái)應(yīng)用程序,在 Program.Main 的開(kāi)頭,或者在 Web 應(yīng)用程序中,在 Application_Start 上:
DbConfiguration.SetConfiguration(new MyCustomSQLDbConfiguration());

TA貢獻(xiàn)1834條經(jīng)驗(yàn) 獲得超8個(gè)贊
自定義 DbConfiguration 也對(duì)我有用?;蛘?,我看到它使用 DbContext 和 DbConnection 構(gòu)造函數(shù)成功運(yùn)行,而不使用任何 DbConfiguration 屬性。
using (var sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["MssqlConnectionString"].ConnectionString))
using (var mssqlDbContext = new MSSQLDbContext(sqlConnection, true))
{
//...
}
using (var mySqlConnection = new MySqlConnection(ConfigurationManager.ConnectionStrings["MysqlConnectionString"].ConnectionString))
using (var mySQLDbContext = new MySQLDbContext(mySqlConnection, true))
{
//...
}
配置中的system.data部分如下。
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL"
type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=8.0.24.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
我可以看到從兩個(gè)數(shù)據(jù)上下文(MSSQL Compact 和 MySQL)檢索的結(jié)果。

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
您可以使用部分類:
public partial class MySqlDBContext : DbContext
{
public MySqlDBContext(string FirstSQLServerDBContext)
: base(configmanager.connectionstrings(FirstSQLServerDBContext)...)
{
}
- 3 回答
- 0 關(guān)注
- 205 瀏覽
添加回答
舉報(bào)