簡體   English   中英

EF 核心具有相同外鍵的多個虛擬屬性

[英]EF core Multiple Virtual Properties with the same foreign key

在實體框架中是否可以對幾個 realted 屬性使用相同的外鍵。 例如:

// There is one table for credit cards. To destinguish between company credit cards and lets say shoppers credit cards there is tag field CustomerType. SO two different credit cards can have the smae EntityId but if CustomerType is different the navigatin property would point to either Client or Company table.
public enum CustomerType
{
   Client,
   Company
}

public class Client
{
   public int Id { get; set; }
   virtual public IEnumerable<CreditCard> CreditCards { get; set; }  
}
public class Company
{
    public int Id { get; set; }
    virtual public IEnumerable<CreditCard> CreditCards { get; set; }  
}

public class CreditCard
{
   public int Id { get; set; }
   //this points to either company or client depending on the customertype field.
   public int EntityId { get; set; }
   public CustomerType Type { get;set;}
   public virtual Client Client { get; set; }
   public virtual Company Company { get; set; }
}
 ......
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   // obviously this is wrong ...
   modelBuilder.Entity<Client>(entity =>
   {
       entity.HasMany(x => x.CreditCards)
           .WithOne(y => y.Client)
           .HasForeignKey(z => z.HolderId);
   });

   modelBuilder.Entity<Company>(entity =>
   {
      entity.HasMany(x => x.CreditCards)
          .WithOne(y => y.Company)
          .HasForeignKey(z => z.HolderId);
   });
 }

或者我應該忘記它並將公司信用卡和客戶信用卡放在不同的表中。 那將是直截了當的。

model 破壞了規范化。 如果公司與客戶信用卡有單獨的表,則從表結構中可以看出,實體也應聲明公司與客戶信用卡。 將您建議的表結構中的 Table-per-Concrete inheritance 與您似乎想在實體中設置的 Table-per-Hierarchy 混淆。 通常最好讓您的實體反映您的數據結構。

EF 可以通過 inheritance 處理這種場景:

public abstract class CreditCard
{
    [Key]
    public int Id { get; set; }
    // card details
}

public class ClientCreditCard : CreditCard
{
    public virtual Client Client { get; set; }
}

public class CompanyCreditCard : CreditCard
{
    public virtual Company Company { get; set; }
}

Company 將擁有一組 CompanyCreditCards,而 Clients 將擁有 ClientCreditCards。

從表的角度來看,您可以有一個帶有信用卡類型鑒別器的 CreditCard 表,盡管公司或客戶的 ID 都可以為空。 (Table-Per-Hierarchy) 來維護與其他實體的 FK 關系。 有一個鑒別器+“EntityId”,它指向或者破壞規范化。 (沒有 FK 可能)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM