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:
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
Regarding @cristi71000 answer, that was the case. my solution was adding AsNoTracking()
as the following:
var dbProject = db.Projects.AsNoTracking()...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With