1

I have model with defined primary key, but now I need to add inheritance to this class from my abstract class. The problem is, that primary key is required also to abstract class. Names of the PK's properties are different and they have to be different.

Example:

public abstract class AbstractModelClass
{
    public int AbstractModelClassId { get; set; } // this key is required but I want him to not to be because I don't want to have 2 PK's
    public string Prop1 { get; set; }
}

public class ModelClass : AbstractModelClass // before this class was not inherited but now I need this
{
    public int ModelClassId { get; set; }
    public int Prop2 { get; set; }
}
d3st1ny
  • 75
  • 1
  • 13
  • This is a suggestion I made on a similar [question](https://stackoverflow.com/a/45834364/5148649) – Scrobi Sep 14 '17 at 08:53

2 Answers2

1

Why can't the primary key be in the abstract class but in database it is different tables? Check out Table per Concrete Type (TPC) approach in EF. Good explanation here:

https://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-3-table-per-concrete-type-tpc-and-choosing-strategy-guidelines

Sample:

public abstract class BillingDetail
{
    [DatabaseGenerated(DatabaseGenerationOption.None)]
    public int BillingDetailId { get; set; }
    public string Owner { get; set; }
    public string Number { get; set; }
}

public class BankAccount : BillingDetail
{
    public string BankName { get; set; }
    public string Swift { get; set; }
}

public class CreditCard : BillingDetail
{
    public int CardType { get; set; }
    public string ExpiryMonth { get; set; }
    public string ExpiryYear { get; set; }
}

public class InheritanceMappingContext : DbContext
{
    public DbSet<BillingDetail> BillingDetails { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<BankAccount>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("BankAccounts");
        });

        modelBuilder.Entity<CreditCard>().Map(m =>
        {
            m.MapInheritedProperties();
            m.ToTable("CreditCards");
        });            
    }
}
Ogglas
  • 62,132
  • 37
  • 328
  • 418
1

In this case I don't see the purpose of AbstractModelClassId in AbstractModelClass so one solution would be not having it.
However is for some reason you need that property, but don't want that it gets into Db table then you could add [NotMapped] attribute to it.

[NotMapped]
public int AbstractModelClassId { get; set; }
borisdj
  • 2,201
  • 3
  • 24
  • 31