Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Can someone explain to me what I am doing wrong?

I am using Entity Framework 6 with MySQL on a C# application. I have a lot of One to Many relationships, and I need to grab all of the associated data to display it on the screen.

With Lazy Loading, it takes a lot of time to pull the data. I am running this query:

Lot foundLot = EntitiesContext.Lots.Where(x => x.ID == lotID).FirstOrDefault();

Which will return the first lot that matches that ID, and when I call to the subsequent children it will load them. This works fine, however its slow.

I wanted to try to do Eager Loading, but when I call to the "Include" function all of my data is mixed up, and the wrong things get associated.

This is how I am doing that:

Lot foundLot = EntitiesContext.Lots.Where(x => x.ID == lotID)
            .Include("Parts")
            .Include("Parts.Bin")
            .Include("Parts.Stations")
            .Include("Parts.Stations.Tools")
            .Include("Parts.Stations.Tools.Measurements")
            .AsNoTracking()
            .FirstOrDefault();

Note: I have also tried using the Include LINQ version

.Include(x => x.Parts.Select(p => p.Stations));

It pulls the Lot, Parts, Bin and Stations correctly but when it pulls the tools it uses the Part ID rather than the associated Station ID.

I have verified my foreign keys are setup properly. I am utilizing Code-First implementation so when I go look at my Tool.cs file:

public int? StationID { get; set; }

[ForeignKey("StationID")]
public virtual Station Station { get; set; }

I define my Foreign Key to the Station ID, and then in my station:

[Key]
public int ID { get; set; }

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Tool> Tools { get; set; }

and I have a migration that will create my foreign key:

AddForeignKey("tools", "StationID", "stations", "ID", true, "FK_Tools_Stations_StationID");

Like I said, the Lazy Loading everything is fine. It's just slow. The Eager Loading mixes the data, why?

Thank you.

question from:https://stackoverflow.com/questions/66064240/ef-eager-loading-vs-lazy-loading

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
413 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...