简体   繁体   中英

Update and edit many to many tables Entity Framework

I have four tables (Locations, Events, MainTags, EventTags) and between the Events table and each one of the other three tables is a many-to-many relationship.

Now I want to edit and display data from those tables on the same page but I'm not sure what is the right way to do it.

For now I'm doing it like this taking the id from each individual entry in the Events table and then searching for the same id in each of the other table, saving those results in a list and later displaying it on the page. ( adc is my connection to the database)

List<Event> allEvents = adc.Events.ToList();
List<Location> testTHis = new List<Location>();

foreach (Event eve1 in allEvents)
{
   var query_test = from a in adc.Locations where a.Id ==  eve1.id select a;
   testTHis = query_test.ToList();
}

But this seems to be rather an intensive work and it doesn't look nice so I'm wondering if there is a much better way to do this especially later when a database has a lot of data in it this doesn't seem like a good idea cause it will take a lot of time to complete. Anyone can help me to figure out a better solution?

Your Event entity should expose 3 navigational properties:

public virtual ICollection<Location> Locations { get; set; }
public virtual ICollection<MainTag> MainTags { get; set; }
public virtual ICollection<EventTag> EventTags { get; set; }

Then when you query for events you tell EF to include all tags/event tags and locations.

context.Events
       .Include(x => x.Locations)
       .Include(x => x.MainTags)
       .Include(x => x.EventTags)
       .ToList()

This will retrieve events as well as their Locations, MainTags and EventTags all together in one query.

One word of warning with include is, each event will have its own Tag/Location, even if its referenced multiple times.

Eg lets say you have 2 Events,

  1. CodePerfDotNetEvent { Tag={ID=1, Name="Blog"} }
  2. MichalCiechanEvent { Tag={ID=1, Name="Blog"} }

When you use include you will get 2 different Tag objects even though they represent the same value in the database.

Otherwise you leave LazyLoading and ProxyGeneration on, and let EF make multiple calls to the database each time you access one of the Locations/EventTags/MainTags virtual properties.

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