Skip to main content

Verify database prior to data insertion via EF

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

Here is the quick solution for this.

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

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 matched with your model class.

Isn’t it a useful tip?
Happy troubleshooting!!!

Comments