【问题标题】:Entity Framework Two foreign key in one table实体框架一张表中有两个外键
【发布时间】:2013-01-22 04:45:23
【问题描述】:

我有两个实体:

public class Person {
    [Key]
    public string Name {get;set;}

    public virtual Phone homePhone {get;set;} 
    public virtual Phone cellPhone {get;set;}
}

public class Phone {
    [Key]
    public int PhoneNumber {get;set;}

    public virtual Person {get;set;} 
}

一个人可以有零个或一个家庭电话和零个或一个手机。 (我认为这是一对一或零关系)。

如何使用 CodeFirst API 使用实体框架对此进行建模。我可以通过将 Person 设置为 Phone 的主键和外键来模拟 Person 和 Phone 之间的一对零/一关系,但是 homePhone 和 cellPhone 如何具有相同的 person 实体?反过来,我可以说 Phone 和 Person 之间存在一对零/一的关系,其中每个 Person 都有两个 Phone 外键?

【问题讨论】:

    标签: c# entity-framework foreign-keys one-to-one


    【解决方案1】:

    您可以添加另一个用于创建电话类型的表,然后每个电话必须至少有一个电话类型:

    public class Person
    {
        [key]
        public string name {get;set;}
    
        public virtual ICollection<Phone> Phones {get;set;}
    }
    
    public class Phone
    {
        [key]
        public int PhoneNumber {get;set;}
    
        public int PhoneTypeId {get;set;}
        public virtual PhoneType PhoneType {get;set;}
    }
    
    public class PhoneType
    {
        [key]
        public int PhoneTypeId {get;set;}
        public string PhoneTypeDescription {get;set}
    }
    

    【讨论】:

      【解决方案2】:

      你应该这样想:

      public class Person {
          [Key]
          public string Name {get;set;}
      
          Public PersonPhone HomePhone{get; set;}
      
          Public PersonPhone CellPhone{get; set;}        
      }   
      
      public class Phone {
          [Key]
          public int PhoneNumber {get;set;}
      }
      
      public class PersonPhone {
          [Key]
          public virtual Phone Phone {get;set;}
      
          [Key]
          public PhoneType PhoneType {get;set;}
      }
      
      public enum PhoneType {
          HomePhone,
          CellPhone 
      }
      

      【讨论】:

      • 但这不会限制一个人拥有两部以上的手机。一个人最多只能拥有一部家庭电话和一部手机
      • 它抛出一个异常,即没有为 PersonPhone 定义键。关键应该是什么
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-06
      • 1970-01-01
      相关资源
      最近更新 更多