2017-09-14 67 views
1

我有定義的主鍵的模型,但現在我需要從我的抽象類繼承這個類。問題是,主鍵也需要抽象類。 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; } 
} 
+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; } 
相關問題