我正在研究Timesheet系统。我第一次使用实体框架,并且对这些关系如何运作感到困惑。
我有以下课程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(浮动)
FriHours(浮动)
Week_WeekId(int)
在我的表格中,我有以下内容:
WeekId --- Firstdayofweek可
1 ------------ 2017年7月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 ...
的定义
这样做的正确方法是什么?
答案 0 :(得分:1)
在读取数据时需要使用Include()子句,以便要求Entity Framework执行JOIN操作并检索相关记录。
Week SelectedWeek = (from w in db.Weeks.Include(x => x.TimeEntries)
where w.WeekId == 1
select w).FirstOrDefault();
答案 1 :(得分:1)
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