I am having a problem with the Entity Framework code-first approach:
public class Entity
{
[Key]
public int Id { get; set; }
public string A { get; set; }
}
public class Context : DbContext
{
public DbSet<Entity> Entities { get; set; }
}
Let's say this is the setup for the Entity Framework. It works. I can create an Entity instance and Add it to the Entities set. Now my problem is: I want to create a subclass of Entity that is a ViewModel passed to some view:
public class EntityViewModel : Entity
{
public String ViewModelProperty { get; set; }
}
Then, when I get back the resulting object from the model binder, I should be able to do this:
public void Action(EntityViewModel vm)
{
db.Entities.Add(vm); // This should work since EntityViewModel inherits Entity
db.SaveChanges();
}
Here, I get the following Exception:
Mapping and metadata information could not be found for EntityType 'EntityViewModel'.
I already tried adding the [NotMapped] attribute to EntityViewModel, this doesn't help. If I manually extract the EntityViewModel properties into a new Entity object, it works:
public void Action(EntityViewModel vm)
{
var entity = new Entity
{
Id = vm.Id,
A = vm.A
};
db.Entities.Add(entity); // This works!!!
db.SaveChanges();
}
Why does the EntityFramework behave this way? Is there a way to tell it to ignore EntityViewModel objects?
Thanks in advance.