How to check if a database schema matches an Entity Framework schema schema?

For my surprise, using the CreateDatabaseIfNotExists context initializer , the line

context.Database.Initialize(true) 

does not throw an exception if the scheme does not match my first code scheme.

Is there a way to check whether the current database matches our schema earlier, for example, we are trying to access an entity whose table no longer exists in the database and the exception is thrown by EF?

+7
source share
2 answers

You can call CompatibleWithModel to determine if the database matches the model. If you set the parameter to true, it will throw an exception if no model data is found in the database.

 bool isCompatible = context.Database.CompatibleWithModel(true); 
+13
source

EF does not crosscheck the database schema with the model each time the application starts. Instead, he searches for a model that is stored in the database (__MigrationsHistory table and before EdmMetadata) and compares this saved model with the model you are using. If the models match, the database will be used. If the models do not match the exception, they will be thrown away. If your database does not have a __MigrationHistory or EdmMetadata table, EF will assume that you are using the basic Database approach with DbContext and your database is model-compliant. If you want to compare the database with your model, you can reset Edmx for your model (using EdmxWriter.WriteEdmx) and use Visual Studio and the EF constructor to get Edmx from the database and compare parts of the SSDL.

+6
source

All Articles