简体   繁体   中英

EntityFramework Mutli-Table Many-to-Many

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?

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}
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM