Entity Framework - many to many with primary key and composite foreign key

坚强是说给别人听的谎言 提交于 2019-12-24 06:43:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!