What Happens When Database Doesn't Match Conventions / Using OnModelCreating() Feature?

This is just basic article and I'm not going to say anything new here but I will say things my way. The very well-known question newbies ask about MVC and Entity Framework is, how does a conceptual database model target the names?



Look at the above image (showing how MVC targets the names), this is just an amateur rough sketch. Now returning to the real question. In the above image, I have all the properties in the "CollegeStudents" class that exactly matches the Database fields.


Study 1


Let's unmatch them by changing the property names in the "CollegeStudents" class, as in:



In the above image you can clearly see that the properties do not match. Now, the biggest issue is that all the "Views", or the UI, is implemented already using "Id", "StudentName" and "StudentAddress", property names. In this case if you run your application you will notice the error "The model backing the 'Students' context has changed since the database was created", suggesting to use "Code First Migration to update the database".



Now, what if you are not a database guy or you don't have control over database. In this situation the "OnModelCreating()" method is relevant. You just need to add some code snippets and you are done.



Using the above new code, we are directing the Entity Framework to use "Name" instead of "StudentName" and "Address" instead of "StudentAddress" whenever the model is created. So, by using this you don't need to update or make any changes in the database. Hope this is clear to you.


Study 2


As in "Study 1", what will happen when "Id" gets unmatched? Let's unmatch it first:



Now, in this case if you run the application you will see the following error:



And the errors are:


One or more validation errors were detected during model generation:


\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'CollegeStudents' has no key defined. Define the key for this EntityType.

\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'std' is based on type 'CollegeStudents' that has no keys defined.


The clear meaning of this error is, there is a key field in database and the system is searching for it but unfortunately we modified the name "Id" to "StudentId" therefore it could not be found. Here is the fix:



Just two modifications, first added the [Key] attribute with "StudentId" property to let the system know "yes this is my new key property" and second add the same thing as we already did in the above Study 1 that is in the "OnModelCreating()" method.


Note: Entity Framework Code First recognizes the key, by default, by name. Valid names are Id or <YourClassName>Id.


Similar Articles