Ali Kleit
Ali Kleit

Reputation: 3649

Why is Entity Framework core loading entity's relations without adding include

I'm using EF core in a .net core project. After fetching data from ef context, the object's entity's (one-to-many etc...) are automatically loaded.

Here's my code:

 public TimeSheetActivity Get(int id)
 {
     DataSets.TimeSheetActivity dbActivity = db.TimeSheetActivities
                                               .Include(k => k.ProjectFile)
                                               .Include(k => k.MeasurementUnit)
                                               .Include(k => k.TypeOfWork)
                                               .Include(k => k.TimeSheetProject)
                                               .FirstOrDefault(k => k.ID == id);

     return dbActivity == null ? null : _mapper.Map<TimeSheetActivity>(dbActivity);
 }


public Project GetActivityProject(int id)
{
    //db.SaveChanges();

    TimeSheetActivity activity = Get(id);

    if (activity == null)
    {
        return null;
    }

    var dbTimeSheetProject = db.TimeSheetProjects.First(k => k.ID == activity.TimeSheetProjectId);

    var dbProject = db.Projects.First(k => k.ID == dbTimeSheetProject.ProjectId);
    // PROBLEM HERE >> dbProject is loading all entities related
    return _mapper.Map<Project>(dbProject);
}

The problem is marked above and commented in Projects context, here's the project class:

public class Project
    {
        public int ID { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime DateAdded { get; set; }

        public int? ParentId { get; set; }
        public int? DepartmentId { get; set; }
        public int? CompanyId { get; set; }


        public virtual Department Department { get; set; }
        public virtual Company Company { get; set; }

        public virtual Project Parent { get; set; }

        public virtual List<Project> Activities { get; set; }
        public virtual List<TimeSheetProject> TimeSheetProjects { get; set; }
        public virtual List<ProjectFile> ProjectFiles { get; set; }

    }

Debugging capture:

Debug

Upvotes: 5

Views: 4850

Answers (2)

Ali Kleit
Ali Kleit

Reputation: 3649

Regarding @cristi71000 answer, that was the case. my solution was adding AsNoTracking() as the following:

var dbProject = db.Projects.AsNoTracking()...

Upvotes: 6

cristi71000
cristi71000

Reputation: 1124

I think the problem is this (excerpt from documentation):

Entity Framework Core will automatically fix-up navigation properties to any other entities that were previously loaded into the context instance. So even if you don't explicitly include the data for a navigation property, the property may still be populated if some or all of the related entities were previously loaded.

https://learn.microsoft.com/en-us/ef/core/querying/related-data#eager-loading

Upvotes: 8

Related Questions