Is it possible to have a EF Context for MySql and SqlServer?

前端 未结 2 681
悲&欢浪女
悲&欢浪女 2021-01-24 06:30

I have two entity framework contexts, one for MySql and one for sql. If I run the app I get the following error

The default DbConfiguration instance was used by          


        
相关标签:
2条回答
  • 2021-01-24 07:18

    My Uow.cs had 2 different contexts as variables. As a result during object initialization the first context's DbConfiguration was silently applied even when I was interested only in the second context. As a result the second context have responded with the same error until I have changed the design.

    update

    More details - I have updated the code to use the same Context for Oracle and MS SQL versions. To provide correspondent db configuration I have added custom config class in the same assembly with the context and use it with DbConfigurationType attribute. In your case it could be something like this:

    public class CustomDbConfiguration : DbConfiguration
    {
        public CustomDbConfiguration()
        {
            if (DbChecker.MySqlInUse)
                SetConfiguration(new MySqlEFConfiguration());
        }
    }
    

    and both contexts are trying to apply it

    [DbConfigurationType(typeof(CustomDbConfiguration))]
    public class ZipCodeContext : DbContext
    {
        public DbSet<ZipCode> ZipCodes { get; set; }
    }
    
    [DbConfigurationType(typeof(CustomDbConfiguration))]
    public class MyContext : DbContext
    {
        public DbSet<MyClass> MyClasses { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-24 07:28

    FYIW - I had the same problem. The only thing that resolved the issue was to add the following code at the beginning of my program's execution.

    var needsToBeInstantiated = new EFDBContextConfiguration();
    EFDBContextConfiguration.SetConfiguration( needsToBeInstantiated );
    
    0 讨论(0)
提交回复
热议问题