Why is not possible to a view model inherit from Model in entity framework

asp.net-mvc, c#, entity-framework, inheritance

Solution

Your question "why is wrong inherit from a Model class?" comes from the wrong assumption this issue is caused by inheritance. It is conceptually not advisable to do so, but technically it should not cause any issues when programmed correctly.

Others have responded already to why it is not a good idea to use entity framework models as (parts of) viewmodels, so I will address the technical issue at hand.

Given you do this:

var modelClass = model.CastToModelClass();
context.ModelClass.Add(modelClass);
context.SaveChanges();

And `CastToModelClass()` returns an EF model, makes your inheritance question irrelevant. The problem must be in the code that prepares and returns a new `ModelClass` entity.

If you do

var entityModel = new ModelClass
{
    Prop1 = model.Prop1,
    Prop2 = model.Prop2,
    // ...
};
context.ModelClass.Add(entityModel);
context.SaveChanges();

You're basically doing the same. That should just work; if it doesn't, you're not properly mapping all properties. The problem does not lie within the inheritance.

Problem

When I was developing an app in work, I got an error: ``` Value cannot be null. Parameter name: input ``` There are a lots of post talking about that so I read them and... No solution. Good to go on. So i checked if there are any property that is not nullable in database model that was trying to be insert and not, all of them where nullable(except the Identity) so that was not the problem. So I realized that the View Model where the error was being thrown was inhering from a Model class and I thought:"could that be the problem?". so I am no longer inheriting from the model and get back to work. Notice that this was not the first time that this happened me, two weeks ago I had the same situation and it was because of it. Why was I inheriting from model class? Because it has +10 properties and I need it to display this values in view but I need also display values from another model class so I create a View Model: ``` class ViewModel: ModelClass{ //ModelClass contains +10 properties //and the current class contains 7 properties public ModelClass CastToModelClass() { return new ModelClass{ /*stuff...*/ }// casting the current properties values to the ModelClass class } } ``` To when i insert the newly casted model is when i get the error: ``` public JsonResult Save(ViewModel model) { var modelClass = model.CastToModelClass(); // here there are not empty properties context.ModelClass.Add(modelClass); context.SaveChanges();// error throw } ``` So my question is, why it is wrong to inherit from a Model class?

Original source