How to check if database schema matches Entity Framework schema?

Eduardo Brites picture Eduardo Brites · Oct 26, 2012 · Viewed 16.4k times · Source

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

context.Database.Initialize(true)

doesn't throw an exception if the schema does not match my code first schema.

Is there a way to validate if the current database matches our schema before, for instance, we try to access a entity, whose table doesn't exist on the database anymore, and an exception is thrown by EF?

Answer

AxdorphCoder picture AxdorphCoder · Aug 22, 2014

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);