I did not find such built-in tools in EF. But my solution is
We enable the possibility of migrations for the context database. To do this, enter the command
enable-migrations
of
Tools → Library Package Manager → Package Manager Console
After executing the command, the folder Migrations should be created in the selected project, and inside this folder is the Configuration.cs file, which contains the migration settings.
In the constructor of this automatically generated class, we disable automatic migration by setting the AutomaticMigrationsEnabled property to false . For example,
internal sealed class Configuration : DbMigrationsConfiguration<ContosoUniversity.DAL.SchoolContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(ContosoUniversity.DAL.SchoolContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. Eg // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } }
Now, when initializing the database context, if the database schema does not fit the described model, an exception will be thrown (without trying to tune the database schema for the model).
Perform explicit context initialization by wrapping it in try / catch
try { using(var context = new MyDb()) { context.Database.Initialize(false); } // БД подходит под модель } catch { // бд не соответствует схеме }
This code can be wrapped in some method that returns a boolean value with the result of checking the conformity of the model and database schema. If an exception occurred, then the DB schema does not match the model.
You can also execute a sql script to check for the existence of a context in the database using the database:
using(var dbContext = new MyDb()) { int result = (dbContext as IObjectContextAdapter).ObjectContext.ExecuteStoreQuery<int>(@" IF EXISTS (SELECT * FROM sys.tables WHERE name = 'TableName') SELECT 1 ELSE SELECT 0 ").SingleOrDefault(); }