How to check if database schema matches Entity Framework schema?

旧街凉风 提交于 2019-11-27 05:59:00

问题


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?


回答1:


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



回答2:


EF does not cross check database schema with model each time you start your application. Instead it is looking for the model that is saved to the database (__MigrationsHistory table and before EdmMetadata) and compare this saved model with the model you are using. If models match then database will be used. If models don't match an exception will be thrown. If you have neither __MigrationHistory nor EdmMetadata table in your database EF will assume that you are using Database first approach with DbContext and your database matches the model. If you want to compare the database with your model you could dump Edmx for your model (using EdmxWriter.WriteEdmx) and use the Visual Studio and EF designer get the Edmx from Database and compare SSDL parts.



来源:https://stackoverflow.com/questions/13089448/how-to-check-if-database-schema-matches-entity-framework-schema

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!