C# 实体框架代码优先-不带主键的抽象模型类

C# 实体框架代码优先-不带主键的抽象模型类,c#,entity-framework,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

我有一个定义了主键的模型,但现在我需要从抽象类向这个类添加继承。问题是,抽象类也需要主键。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; }
}

为什么主键不能在抽象类中,但在数据库中却是不同的表?查看EF中每种混凝土类型(TPC)的
方法。这里有很好的解释:

样本:

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");
        });            
    }
}
公共抽象类BillingDetail
{
[DatabaseGenerated(DatabaseGenerationOption.None)]
public int BillingDetailId{get;set;}
公共字符串所有者{get;set;}
公共字符串编号{get;set;}
}
公共类银行账户:BillingDetail
{
公共字符串BankName{get;set;}
公共字符串Swift{get;set;}
}
公共类信用卡:BillingDetail
{
public int CardType{get;set;}
公共字符串ExpiryMonth{get;set;}
公共字符串ExpiryYear{get;set;}
}
公共类InheritanceMappingContext:DbContext
{
公共数据库集计费详细信息{get;set;}
模型创建时受保护的覆盖无效(DbModelBuilder modelBuilder)
{
modelBuilder.Entity().Map(m=>
{
m、 MapInheritedProperties();
m、 可转帐(“银行账户”);
});
modelBuilder.Entity().Map(m=>
{
m、 MapInheritedProperties();
m、 ToTable(“信用卡”);
});            
}
}

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

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

这是我在类似问题上提出的建议