Evgeni Dimitrov
Evgeni Dimitrov

Reputation: 22506

EntityFramework requires migration when subclass entity

I have an entity:

namespace Project.Models.DbModels
{
    public class MyEntity
    {
        public long Id { get; set; }
        public long Number { get; set; }
        public SomeOtherEntity otherEntity{ get; set; }
    }
}

I subclassed it to add a list of SomeOtherEntity(as a view model) to use it in a view as dropdown.

    namespace Project.Models.ViewModels
    {
        public class MyNewEntity : MyEntity
        {
            public List<SomeOtherEntity> otherEntities { get; set; }
        }
    }

And the Db context is:

namespace DskVault.Models.DbModels
{
    public class MyDbContext : DbContext
    {
        public MyDbContext()
            : base("DefaultConnection")
        { 
        }

        public DbSet<MyEntity> MyEntities { get; set; }

    }
}

Notice that MyNewEntity is not in the context.

The problem is that when I execute Add-Migration the framework ties to add column to SomeOtherEntity that references the view-model(MyNewEntity) and discriminator column in MyEntity. How can i overcome this. I don't want the drived class(MyNewEntity) to be managed by the EF and the database to be updated acordingly.

Upvotes: 0

Views: 68

Answers (1)

Colin
Colin

Reputation: 22595

Sub-classing an entity creates a new class of entity - which will be managed by EF. So don't sub-class to create view models, map instead.

Sub-classing will often be an inappropriate technique because you will often want your view model to contain less fields than your entity.

Upvotes: 1

Related Questions