我有两个数据库提供程序:SQL Server和MySql。 EF使DbProviderFactory
感到困惑。 EF创建了我的DbContext
,并使用SQL Server连接字符串设置了工厂mySql!
我的连接字符串:
<add name="MsSqlConnection" providerName="System.Data.SqlClient" connectionString="Data Source=myServer;Initial Catalog=MyCatalog;Persist Security Info=True;User ID=user;Password=password"/>
<add name="MySqlConnection" providerName="MySql.Data.MySqlClient" connectionString="Server=server;Database=db;Uid=user;Pwd=password;"/>
我的环境:
namespace DAL.EntityFramework.MySql
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class MySqlContext: DbContext
{
public MySqlContext(string connectionName) : base(nameOrConnectionString: connectionName)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new SomeMap());
}
}
}
namespace DAL.EntityFramework.App
{
public class ApplicationContext : DbContext
{
public ApplicationContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new SomeMap());
}
}
}
在另一个项目中,一切正常,执行相同操作
答案 0 :(得分:0)
这是我一生中最好的错误! 多亏了迈克尔,问题才是DI(团结)! 我注册了我的依赖项:
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<MySqlContext>(new InjectionConstructor("MySqlGlobalConnectionTest"));
container.RegisterType<ApplicationContext>(new InjectionConstructor("ApplicationConnectionTest"));
container.RegisterType<MsSqlReadOnlyContext>(new InjectionConstructor("MsSqlApplicationConnection"));
container.RegisterType<IUnityOfWork, UnityOfWork>();
}
问题出在执行的顺序上!
public class UnityOfWork : IUnityOfWork
{
private MySqlContext mySqlContext;
private ApplicationContext applicationContext;
private MsSqlReadOnlyContext msSqlReadOnlyContext;
public UnityOfWork(
ApplicationContext applicationContext,
MsSqlReadOnlyContext msSqlReadOnlyContext,
MySqlContext mySqlContext // <-- When I put on the first place - there is an error of definition of factory!
)
{
this.mySqlContext = mySqlContext;
this.applicationContext = applicationContext;
this.msSqlReadOnlyContext = msSqlReadOnlyContext;
}
}
这是一个非常奇怪的错误。显然与UnityDI有关的问题