2

There are already several related questions on StackOverflow but I'm having trouble making sense of the answers.

I'm using Code First (with annotations, not fluent API) and trying to create a composite primary key on one table, where the primary key is composed of two foreign keys and each foreign key points to a different table.

In a nutshell, I have a Conversations table which has (among other things) columns for EmployeeId and CustomerId. The EmployeeId column references the Employees table and the CustomerId column references the Customers table.

My models look like this (simplified somewhat):

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
}

Attempting to look up an employee by phone number, like this...

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

...results in the following error:

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

What am I missing? I need to ensure that there is only ever one Conversation record between a given employee and customer, and both IDs have to be valid.

Joshua Smith
  • 944
  • 6
  • 10
  • This answer might help: http://stackoverflow.com/questions/14873169/creating-composite-key-entity-framework – DLeh Jan 08 '14 at 21:38

1 Answers1

0

Adding the column order data annotation will setup composite keys [Column(Order = 0)] and you can just mark them as foreign keys like you normal would. Any Column given an order number will be included in the composite key, in the order they are numbers so 0 then 1 then 2 etc.

Matthew Verstraete
  • 6,335
  • 22
  • 67
  • 123