EF核心具有相同外键的多个虚拟属性



在实体框架中,是否可以对多个实际属性使用相同的外键。例如:

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

或者我应该忘记这件事,把公司信用卡和客户信用卡放在不同的表格里。那将是一条直线。

该模型破坏了规范化。从表格结构来看,如果公司与客户信用卡有单独的表格,那么实体也应该声明公司与客户的信用卡。它混淆了您提议的表结构中的"每具体表"继承与您似乎希望在实体中设置的"每层次表"。通常最好让您的实体镜像您的数据结构。

EF可以通过继承来处理这种情况:

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

公司将拥有一组CompanyCreditCards,而客户将拥有ClientCreditCards。

从表的角度来看,您可以有一个带有信用卡类型鉴别器的CreditCard表,尽管它对公司或客户都有可以为null的ID。(每个层次的表(以保持与其他实体的FK关系。具有鉴别器+";EntityId";这将指向或打破正常化。(不可能使用FK(

最新更新