问题
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:
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.
来源:https://stackoverflow.com/questions/26787976/entity-framework-many-to-many-with-primary-key-and-composite-foreign-key