如何在Entity Framework中创建由两个表的外键组成的复合主键?

时间:2014-01-08 20:39:59

标签: c# entity-framework

StackOverflow上已经有几个相关问题,但我无法理解答案。

我正在使用Code First(带注释,而不是流畅的API)并尝试在一个表上创建复合主键,其中主键由两个外键组成,每个外键指向不同的表。 / p>

简而言之,我有一个Conversations表,其中包含EmployeeIdCustomerId的列(除其他外)。 EmployeeId列引用Employees表,CustomerId列引用Customers表。

我的模型看起来像这样(有点简化):

public class Employee
{
    [Key]
    public Guid Id {get; set;}

    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(100)]
    public string LastName { get; set; }

    [MaxLength(20)]
    public string PhoneNumber { get; set; }
}

public class Customer
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    [MaxLength(100)]
    public string FirstName { get; set; }

    [Required]
    [MaxLength(100)]
    public string LastName { get; set; }

    [MaxLength(20)]
    public string PhoneNumber { get; set; }
}

public class Conversation
{
    public Guid Id { get; set; }

    [Key, Column(Order=0)]
    public Guid CustomerId {get; set;}

    [Key, Column(Order=1)]
    public Guid EmployeeId {get; set;}

    [ForeignKey("CustomerId")]
    public Customer Customer {get; set;}

    [ForeignKey("EmployeeId")]
    public Employee Employee {get; set;}

    // ... snip other unimportant properties
}

尝试通过电话号码查找员工,例如......

public Employee FindByPhoneNumber(string phoneNumber)
{
    return _context.Employees.SingleOrDefault(e => e.PhoneNumber.Equals(phoneNumber));
}

...导致以下错误:

System.Data.Entity.Edm.EdmAssociationConstraint: The number of properties in the Dependent and Principal Roles in a relationship constraint must be identical.

我错过了什么?我需要确保给定员工和客户之间只有一条Conversation条记录,并且这两条ID必须有效。

1 个答案:

答案 0 :(得分:0)

添加列顺序数据注释将设置复合键[Column(Order = 0)],您可以像正常一样将它们标记为外键。任何给定订单号的列都将包含在复合键中,按照它们是数字的顺序,0然后是1然后是2等。