EntityFramework Mutli-Table Many-to-Many

雨燕双飞 提交于 2019-12-04 02:35:39

问题


I'm working with EF4.1 Code First and am trying to create some Many-to-Many relationship tables where there tables would need to be linked. Please see small snippet of code beloow:

class Event
{
    int EventId { get; set; }
    ICollection<Contact> Contacts { get; set; }
}

class Contact
{
    int ContactId { get; set; }
    ICollection<Relation> Relations { get; set; }
}

class Relation
{
    int RelationId { get; set; }
    string Name { get; set; }
}   

So the Contacts object can have many different types of Relationship, such as "Mother", "Father", "Brother", etc.

I need to track some kind of Event where a Contact attended, but I want to know how he is related to the person hosting the Event. So for example, was he the Eventer's Brother, Father or Husband? At another event, the same person could show up, but be the Eventer's Brother-in-Law.

Event to Contact is Many-to-Many; Relation to Contact is One-to-Many.

In SQL, we would just made a link table and have all three properties Id's there (EventId, ContactId, RelationId); however, in Code First, how would you represent this relationship?


回答1:


Same as database you have to create a mapping entity just like ContactEvents like mapping table in database.

class Event
{
  int EventId { get; set; }
  ICollection<ContactEvent> ContactEvents { get; set; }
}

class ContactEvent
{
  int EventId {get;set;}
  int ContactId {get;set;}
  public virtual Event Event {get; set;}
  public virtual Contact Contact {get;set;}
}

class Contact
{
   int ContactId { get; set; }
   ICollection<ContactEvent> ContactEvents { get; set; }
   ICollection<Relation> Relations { get; set; }
}

class Relation
{
  int RelationId { get; set; }
  string Name { get; set; }
  public virtual Contact Contact {get; set}
}   


来源:https://stackoverflow.com/questions/10690467/entityframework-mutli-table-many-to-many

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