How to disable model caching in Entity Framework 6 (Code First approach)

后端 未结 4 457
猫巷女王i
猫巷女王i 2020-12-31 04:36

Following MSDN documentation we can read:

The model for that context is then cached and is for all further instances of the context in the app domain.

4条回答
  •  生来不讨喜
    2020-12-31 04:57

    Here is similar question

    The only available approach comes from the Program Manager of the Entity Framework team (Rowan Miller (MSFT)):

    We removed CacheForContextType in CTP5, we originally intended it to be used when folks wanted to use the same context in the same AppDomain with different models. The issue is that it would create the model on every initialization and didn't allow any way to cache a series of models and choose which one to use during each initialization. Model creation is expensive so we wanted to promote a better pattern.

    The pattern we recommend is to externally create a ModelBuilder -> DbDatabaseMapping -> DbModel for each model you want to use. The DbModel should be cached and used to create context instances. The ModelBuilder -> DbModel workflow is a little messy and the class names aren't great, they will be tidied up for RTM.

    I've tried the following approach:

    1. Move all operations which were inside OnModelCreating event handler to a new function which creates DbModelBuilder (it's more likely you will pass DbConnection as a parameter to this function)
    2. Get DbModel via DbModelBuilder.Build(DbConnecton)
    3. Get DbCompiledModel via DbModel.Compile()
    4. Create new constructor for DbContext with parameters (DbConnection, DbCompileModel, bool) and pass previously created DbCompiledModel inside it

    The result was that I can change parameters of DbCompiledModel every time I call DbContext constructor. That was all I needed.

提交回复
热议问题