1

I have two entities (Case and Person) in a many-to-many relationship with an extra data field(CasePerson with PersonType) on the relationship table.

public class Case {  
    public int Id;  

    public List<CasePerson> CasePeople;
}  

public class Person {  
    public int Id;  

    public List<CasePerson> CasePeople;  
}  

public class CasePerson {  
    public int Id;  
    public int CaseId;  
    public int PersonId;  
    public string Type;  

    public Person Person;  
    public Case Case;  
}  

I'd like to create a composite key on the relational table such that the pairing of a person with a case is unique. I'd also like to maintain a separate primary key on the CasePerson table for ease of manipulation through my Web API controllers. Is there a way in EF or Fluent API to define both keys on this CasePerson table?

  • 1
    possible duplicate of [Creating Composite Key Entity Framework](http://stackoverflow.com/questions/14873169/creating-composite-key-entity-framework) – Rufus L Nov 06 '14 at 19:53
  • 1
    I'm not trying to include a composite key as a foreign key of the relationship; rather, I'm trying to guarantee that the combination {CaseId, PersonId} is unique for every CasePerson. I know that I can make this a composite primary key, but I do not want to drop the already-existing primary key Id from CasePerson. – user3897692 Nov 06 '14 at 20:36
  • I was able to accomplish this by adding `[Index("IX_CasePerson", 1, IsUnique=true)]` to the PersonId and `[Index("IX_CasePerson", 2, IsUnique=true)]` to the CaseId. This unique index forces the column pairing to be unique. – user3897692 Nov 07 '14 at 20:29

1 Answers1

0

I was able to accomplish this by adding
[Index("IX_CasePerson", 1, IsUnique=true)]

to the PersonId and

[Index("IX_CasePerson", 2, IsUnique=true)]

to the CaseId. This unique index forces the column pairing to be unique.