Saisujithreddy
Saisujithreddy

Reputation: 92

Accessing data in Entity Framework relationship tables

I am trying to access the data in the relationship table created by Entity Framework: I have two tables (posting the corresponding models here)

I have models for Event and Child, but not for ChildEvent.

Each Event has multiple children and each Child has multiple events as it is a many-to-many relationship. Now I am able to add and delete the entries into the tables. But when I am trying to access the children associated with each event, I am getting a null.

I have tried googling and I found some posts on easy loading. I have tried turning that off but the problem persists still. Is there any way I can get the children associated with each event. I do not have a model for ChildEvent? I cannot directly query the ChildEvent table.

Public Class Event {       // This is the event model
   public int EventId      // This is the primary key
   public int EventName

   public virtual ICollection<Child> Children // used to reference Child table
}

Public Class Child {       // This is the Child Model
   public int ChildId      // primary key
   public string FirstName 
   public virtual ICollection<Event> Events // used to refer to Event table
}

I have the relationship table created the by Entity Framework

ChildEvent:

    public int ChildId { get; set; }
    public int EventId { get; set; }

Upvotes: 2

Views: 198

Answers (1)

DDiVita
DDiVita

Reputation: 4265

This will ensure that Entity Frameowrk knows how you want your Many To Many relationships setup. This way Lazy Loading will work and EF will map Events to Children and Children to Events.

 public class EventMap: EntityTypeConfiguration<Event>
        {
             public EventMap()
             {
                 HasMany(e => e.Children)
                  .WithMany(c => c.Events)
                  .Map(m =>
                     {
                      m.MapLeftKey("EventId");  
                      m.MapRightKey("ChildId"); 
                      m.ToTable("Event_Children");
                  });
             }
        }

Upvotes: 0

Related Questions