实体框架代码优先 - 没有主键的抽象模型类

时间:2017-09-14 08:48:45

标签: c# entity-framework

我有定义主键的模型,但现在我需要从我的抽象类中为这个类添加继承。问题是,主键也需要抽象类。 PK的属性名称不同,它们必须不同。

示例:

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; }
}

2 个答案:

答案 0 :(得分:1)

为什么主键不能在抽象类中,但在数据库中它是不同的表?查看EF中的Table per Concrete Type (TPC)方法。这里有很好的解释:

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

样品:

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");
        });            
    }
}

答案 1 :(得分:1)

在这种情况下,我没有在 AbstractModelClass 中看到 AbstractModelClassId 的目的,所以一个解决方案就是没有它。
但是出于某种原因,您需要该属性,但不希望它进入Db表,然后您可以向其添加[NotMapped]属性。

[NotMapped]
public int AbstractModelClassId { get; set; }