How to use Entity Framework code - first with a newer version of the database model

Perhaps a strange question, but we have a scenario in which we want to use the Entity Framework code first in an environment that can have a database with a newer / higher version than the code itself.

Let me clarify something. We have several solutions that use the base assembly, which contains a common database used by all solutions. The solutions are mainly sites and applications that are deployed to several different Azure sites. Thus, the solution works next to each other. The only thing they use is the Azure database.

Now the script will come into play. When we update the database model in the kernel assembly and update one of the solutions in Azure. The base database will be updated when the model is loaded inside this solution. No problem there, it works like a charm ...

The problem starts when one of the other solutions loads. These other solutions still use the previous kernel assembly, which now has an outdated EF CF model compared to the database model to which they connect. Therefore, a beautiful exception will be thrown as shown below.

The model supporting the context '{NAME}' has changed since the database was created. Either manually delete / update the database, or call Database.SetInitializer with an instance of IDatabaseInitializer. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database and possibly start it with new data.

The question is whether we can make the model simply load and ignore changes made to the database. We have a policy that allows us to apply not only changes to the database, so the model should be able to load without any problems.

Thanks in advance for the information and advice!

+4
source share
2 answers

( , ), , null:

    public PortalDbContext()
        : base("name=PortalConnectionString")
    {
        Database.SetInitializer<PortalDbContext>(null);
    }

:

public class BlogContextCustomInitializer : IDatabaseInitializer<BlogContext>
{
    public void InitializeDatabase(BlogContext context)
    {
        if (context.Database.Exists())
        {
            if (!context.Database.CompatibleWithModel(true))
            {
                // Do something...
            }
        }
    }
}
+2

EF Code-First, .

, - .

: "Solution A", "A" , - . !. , , , -, " B" , , " B", ? " B" , ? "B" , , "A" , , , , "B" , ?

, , , , , , ? , "A" "B" ?

, , , . . , , DbContext. DbContext . Entities DbContext, Entities. . . , DbContext , . , , , , .

EF6 DbContext , , , DbContext, . , , DbContext ( , ). , (, ), , , (, ).

+2

All Articles