实体框架一个表中的两个外键

时间:2013-01-22 04:45:24

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

我有两个实体:

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

一个人可以拥有零个或一个homePhone和零个或一个cellPhone。 (我认为这是一对一或零关系)。

如何使用CodeFirst API使用Entity Framework对此进行建模。我可以通过将Person设置为Phone的primarykey和foreignkey来建模Person和Phone之间的一对一/零关系,但是homePhone和cellPhone如何才能拥有同一个人实体?换句话说,我可以说Phone和Person之间有一对一/零关系,其中每个人有两个Phone外键?

2 个答案:

答案 0 :(得分:0)

你应该想到这样的事情:

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 
}

答案 1 :(得分:0)

您可以添加另一个用于创建手机类型的表格,然后每部手机必须至少包含一种手机类型:

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}
}
相关问题