我正在使用时间表系统。我是第一次使用Entity Framework,但对关系的工作方式感到困惑。

我有以下课程,Week

public class Week
{
    public int WeekId { get; set; }
    public DateTime FirstDayOfWeek { get; set; }
    public List<TimeEntry> TimeEntries { get; set; }
    public Week()
    {
        TimeEntries = new List<TimeEntry>();
    }
}


并且每个星期包含许多TimeEntries

public class TimeEntry
{
    public int TimeEntryID { get; set; }
    public double MonHours { get; set; }
    public double TueHours { get; set; }
    public double WedHours { get; set; }
    public double ThuHours { get; set; }
    public double FriHours { get; set; }
}


EF为这些表创建表的方式如下:

dbo.Weeks
WeekId(int)
FirstDayOfWeek(日期时间)

dbo.TimeEntries
TimeEntryId(int)
MonHours(浮动)
TueHours(浮动)
WedHours(浮动)
ThuHours(浮动)
星期五(浮动)
Week_WeekId(int)

在我的表格中,我有以下内容:

WeekId --- FirstDayOfWeek
1 ------------ 2017-07-31

TimeEntryId --- MonHours --- TueHours ...- Week_WeekId
1 ----------------- 1 --------------- 2 ...------------ -1
2 ----------------- 0 --------------- 1 ...------------ -1

(为绘制错误的表格致歉!)

问题是,当我尝试使用Linq从控制器中检索数据时,它不会拉回TimeEntries列表。

这是我正在使用的查询:

Week SelectedWeek = (from w in db.Weeks
  where w.WeekId == 1
  select w).FirstOrDefault();


但是,SelectedWeek.TimeEntries的计数为零吗?

我还尝试了相反的方法(从非EF角度看,这似乎更合乎逻辑):

var timeEntries = from te in db.TimeEntries
  where te.week_weekId == 1
  select te;


但这给出了错误:


  TimeEntry不包含week_weekId的定义...


什么是正确的方法?

最佳答案

Week SelectedWeek = (from w in db.Weeks
  where w.WeekId == 1
  select w).FirstOrDefault();


上面的查询导致SelectedWeek.TimeEntries的计数为零,因为它没有被延迟加载或延迟加载。您需要为TimeEntries添加虚拟关键字,也可以依靠快速加载

Lazy Loading
public virtual ICollection<TimeEntry> TimeEntries { get; set; }

Or

Eager Loading
Week SelectedWeek = db.Weeks.Include("TimeEntries").Where(w => w.WeekId == 1).FirstOrDefault();

Or

Explicit Loading
var selectedWeek = db.Weeks.Find(1);

// Load the TimeEntries related to a given Week
context.Entry(selectedWeek ).Collection(t => t.TimeEntries).Load();


有关在EF中加载相关实体的进一步阅读:https://msdn.microsoft.com/en-us/library/jj574232(v=vs.113).aspx

10-08 14:17