When Database Doesn't Match Conventions or Using OnModelCreating Feature

This is just a basic article and I'm not going to talk about anything new here but I will explain things in my way.
 

 

The very well-known question a newbie asks about MVC and the Entity Framework is how does any conceptual database model communicate; in other words how to actually target the names?
 

 


 

Look at the preceding 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 property names in the "CollegeStudents" class.
 

 


In the above image you can clearly see that the properties do not match. Now, the biggest issue is 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 receive the error "The model backing the "Student; context has changed since database was created" suggesting to use "Code First Migration to update database".
 

 


 

Now, what if you are not a database guy or you don't have controller 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 the database and the system is searching for it but unfortunately we modified the name "Id" to "StudentId" so it could not be found. Here is the fix:
 

 


 

Just two modifications, first add the [Key] attribute with "StudentId" property to let the system know "yes this is my new key property" and second added 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.

 

I hope you like this. Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all