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 in 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 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 ‘Student; context has changed since database was created” error 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 Entity Framework to use ‘Name’ instead of ‘StudentName’ and ‘Address’ instead of ‘StudentAddress’ whenever the model gets 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 unmatched it first:


Now, in this case if you run the application you will see 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 above Study 1 that is in ‘OnModelCreating()’ method.

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

I hope you like this. Thanks.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System