实体框架。混淆DbProviderFactory

时间:2018-12-14 15:27:16

标签: c# entity-framework

我有两个数据库提供程序: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());
        }
    }
}

enter image description here

在另一个项目中,一切正常,执行相同操作

1 个答案:

答案 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有关的问题