EF 6,多个导航属性建议

时间:2017-10-22 22:58:27

标签: c# entity-framework

这是EF6,代码优先。我是EF的新手。

我有一个类FollowUp.cs(用于CRM):

public class FollowUp
{
   public int FollowUpId { get; set; }
   public int? ProspectId { get; set; }        
   public int? CustomerId { get; set; }        
   public int? ContractorId { get; set; }        

   [ForeignKey("ProspectId")]
   public virtual Prospect Prospect { get; set; }
   [ForeignKey("CustomerId")]
   public virtual Customer Customer { get; set; }
   [ForeignKey("ContractorId")]
   public virtual Contractor Contractor { get; set; }
   ...

后续记录可以是客户,潜在客户或承包商(注意:这些类非常不同,并且它们不会从公共基类继承)。我对拥有三个可以为空的外键属性(ProspectId等)并不感到兴奋 - 特别是因为将来可以添加更多。

我想的只是使用一个外键属性和一个FollowUpEntityType属性来指示键引用的实体类型:

public class FollowUp
{
   public int FollowUpId { get; set; }
   public int FollowUpEntityId { get; set; }        // The Id of the Prospect or Customer or Contractor (as indicated by FollowUpEntityType)
   public FollowUpEntityType FollowUpEntityType { get; set; } // An enum (Prospect, Customer, Contractor)

   public virtual Prospect Prospect { get; set; }
   public virtual Customer Customer { get; set; }
   public virtual Contractor Contractor { get; set; }
   ...

在实际的数据库中,EF仍然需要创建多个FK,但我不必在类中有多个。但是使用这种方法,甚至可以使导航属性工作(没有很多复杂性)?

在我看来,尽管有多个可以为空的FK属性,但第一种方法是最可行的方法,但我想得到一些关于如何最好地处理这种情况的反馈/建议。

0 个答案:

没有答案
相关问题