Entity Framework: How to avoid Discriminator column from table?

前端 未结 7 1848
无人及你
无人及你 2020-12-08 07:10

I have the following table created using Entity Framework Code First approach.

  1. How do I modify the C# code so that the unwanted Discriminato
7条回答
  •  忘掉有多难
    2020-12-08 07:43

    Sample code to remove Discriminator column and get column named PaymentId as discriminator instead, therefore solving both your questions. Based on Microsofts Fluent Api original documentation.

    https://msdn.microsoft.com/en-us/library/jj591617%28v=vs.113%29.aspx?f=255&MSPPError=-2147217396

    public enum MyEnum
    { 
        Value1, Value2
    }
    
    public class MyBaseClass
    
    { 
        [NotMapped]
        public MyEnum PaymentId { get; protected set; }
    }
    
    public class DerivedOne: MyBaseClass
    {
        public DerivedOne()
        {
            PaymentId = MyEnum.Value1;
        } 
    }
    
    public class DerivedTwo: MyBaseClass
    {
        public DerivedTwo()
        {
            PaymentId = MyEnum.Value2;
        }
    }
    
    public class MyDbContext : DbContext
    {
        DbSet MyBaseClass { get; set; }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
    
            modelBuilder.Entity()
                .Map(x => x.Requires("PaymentId").HasValue((int)PaymentId.Value1))
                .Map(x => x.Requires("PaymentId").HasValue((int)PaymentId.Value2));
        }
    }
    

提交回复
热议问题