Can I specify a discriminator column with a table-per-type mapping?

前端 未结 2 440
误落风尘
误落风尘 2020-12-17 14:28

I have a class hierarchy that I want to map across several tables using Entity Framework 4.1 Code First. It\'s like table-per-type (TPT) but I also want a discrimator column

相关标签:
2条回答
  • 2020-12-17 14:56

    Unfortunately this is not supported. Discriminator column can be used only in TPH. TPT differs entity types by mapped tables and it always produces those terrible queries. It could be nice feature so perhaps suggestion on Data UserVoice would make it implemented one day.

    Update

    There is already a suggestion on user voice for this titled "Discriminator column support in TPT inheritance".

    0 讨论(0)
  • 2020-12-17 15:11

    I did an override on SaveChanges to accomplish something similar. I simply added an attribute onto the abstract class called Descriminator and set it based on the Concrete Class Name anytime something new is added.

    public class MyContext : DbContext
    {        
        public override int SaveChanges()
        {
            foreach (var item in ChangeTracker.Entries().Where(x=>x.Entity is MyAbstractClass && x.State == EntityState.Added))
            {
                ((MyAbstractClass)item.Entity).Descriminator = item.Entity.GetType().Name;
            }
            return base.SaveChanges();
        }
    }
    
    0 讨论(0)
提交回复
热议问题