Question

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?

Was it helpful?

Solution

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}
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top