Verify Database Prior To Data Insertion Using EF

Recently, one of my colleagues got a requirement of inserting data into a database using EF. His issue was - how to verify if the database schema is proper, or say, all the columns in the tables matched with his POCO entities. I bet a few of you must have come across similar scenarios.

Here is a quick solution to this.

In such scenarios, developers can perform a schema compatibility check prior to inserting any data into the columns in order to ensure that the model class still holds good with database tables.

  1. bool isModelValid = yourContext.Database.CompatibleWithModel(true);  
In the above method, passing the correct boolean value will do the trick for us. If the parameter value passed is true, then the framework will throw an exception if the schema doesn’t match with your model class.

Isn’t it a useful tip?

Happy troubleshooting!
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now