2017-09-14 7 views
1

定義済みの主キーを持つモデルがありますが、今では抽象クラスからこのクラスに継承を追加する必要があります。問題は、主キーが抽象クラスにも必要であるということです。 PKのプロパティの名前は異なり、それらは異なる必要があります。Entity Frameworkコードファースト - 主キーのない抽象モデルクラス

例:

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

これは私が同様の[質問](https://stackoverflow.com/a/45834364/5148649)で提案したものです。 – Scrobi

答えて

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

この場合は、私がの目的はその一つの解決策は、それを持っていないだろうAbstractModelClassをAbstractModelClassId表示されません。
しかし、何らかの理由でそのプロパティが必要ですが、Dbテーブルに入ることを望まない場合は、[NotMapped]属性を追加できます。

[NotMapped] 
public int AbstractModelClassId { get; set; } 
関連する問題