为什么实体框架核心加载实体的关系而不添加包含

时间:2019-10-21 06:43:39

标签: c# entity-framework linq asp.net-core entity-framework-core

我在.net核心项目中使用EF核心。从ef上下文中获取数据后,对象的实体(一对多等)会自动加载。

这是我的代码:

public void Method1(object someClassAsTSender, object parameter)
 {
   //i think parametertype = parameter...
   MessagingCenter.Subscribe<someClassAsTSender, object> (this, "messageKey", (message, args) =>
    {
       //convert the type (e.g  string data = args as string)
       Device.BeginInvokeOnMainThread(async () =>
        {
          //await do;
        });
    }
   );
 }

该问题已在上方标记并在 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); } 上下文中进行了注释,这是项目类:

Projects

调试捕获:

Debug

2 个答案:

答案 0 :(得分:3)

我认为问题是这样的(摘自文档):

  

Entity Framework Core将自动将导航属性修复为先前加载到上下文实例中的任何其他实体。因此,即使您未明确包含导航属性的数据,如果先前已加载了部分或全部相关实体,该属性仍可能被填充。

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

答案 1 :(得分:0)

关于@ cristi71000答案,就是这种情况。我的解决方案是将AsNoTracking()添加如下:

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