How should I create secondary DbContext using ContextProvider.EntityConnection?

后端 未结 1 1239
挽巷
挽巷 2020-12-22 03:39

I\'m using breeze with Code First EF. My production DbContext has IDatabaseInitializer that throws an exception if !context.Database.CompatibleWithModel(true).

相关标签:
1条回答
  • 2020-12-22 04:13

    During SaveChanges, Breeze's EFContextProvider creates a DbContext instance using the default constructor. This happens prior to BeforeSaveEntity() and BeforeSaveEntities(). So you can rely on that first DbContext instance to check compatibility before your second DbContext instance is created.

    In your DbContext, set the database initializer only in the default constructor. In the constructor that takes a DbConnection, set the initializer to null:

    public MyDbContext() : base()
    {
        Database.SetInitializer(new CompatibilityCheckingInitializer<MyDbContext>);
    }
    
    public MyDbContext(DbConnection connection) : base(connection, false)
    {
        Database.SetInitializer(null);
    }
    

    This way, you can re-use the database connection on your second DbContext, but still have the initializer working on your first.

    Naturally, you are still free to create DbContexts using any constructor you want, as you would have prior to Breeze 1.4. Using the EntityConnection property in your constructor is suggested as a way to help you conserve database connections.

    0 讨论(0)
提交回复
热议问题