Entity Framework 在实体列表中预先加载实体列表
Entity Framework eager loading entity list within entity list
我遇到了一个问题:我有一个 table,它引用了另一个 table,它有一个引用列表,另一个 table,它有另一个列表参考文献,我想急切加载所有这些。
基本上,这个想法是:
public class User {
public ClassL1 l1 { get; set; }
}
ClassL1 {
public List<ClassL2> l2 { get; set; }
}
ClassL2 {
public List<ClassL3> l3 { get; set; }
}
ClassL3 {
//some basic string or int values
}
目前,我正在尝试用这样的东西加载它,但无济于事:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.ThenInclude(l2List => l2List.Select(l2Single => l2Single.l3))//This doesn't work
//.Include(u => u.l1.l2.Select(l2Single => l2Single.l3)) //Neither does this
.First();
如果 select 不起作用,我应该如何加载列表列表?任何帮助将不胜感激。
编辑:
好吧,因为这显然是一个开放的错误,我做了一个愚蠢的修复,并让它像这样工作:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.First();
for (int i = 0; i < user.l1.l2.Count; i++)
{
user.l1.l2[i].l3 = context.l3DB
.Where(p => p.l2.Id == user.l1.l2[i].Id)
.ToList();
}
为了让它起作用,我在 类 中添加了引用(到 parents)。
例如:
public class ClassL2 {
public List<ClassL3> l3 { get; set; }
public ClassL1 l1 { get; set; }//reference to parent
}
检查这个:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.ThenInclude(l2 => l2.l3)
.First();
这个怎么样:
user = (from usr in context.Users
where usr.UserName == model.Username
select new
{
usr,
usr.l1,
l2List = from l2 in usr.l1.l2
select new
{
l2,
l2.l3
}
}).AsEnumerable().Select(m => m.usr).First();
我遇到了一个问题:我有一个 table,它引用了另一个 table,它有一个引用列表,另一个 table,它有另一个列表参考文献,我想急切加载所有这些。
基本上,这个想法是:
public class User {
public ClassL1 l1 { get; set; }
}
ClassL1 {
public List<ClassL2> l2 { get; set; }
}
ClassL2 {
public List<ClassL3> l3 { get; set; }
}
ClassL3 {
//some basic string or int values
}
目前,我正在尝试用这样的东西加载它,但无济于事:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.ThenInclude(l2List => l2List.Select(l2Single => l2Single.l3))//This doesn't work
//.Include(u => u.l1.l2.Select(l2Single => l2Single.l3)) //Neither does this
.First();
如果 select 不起作用,我应该如何加载列表列表?任何帮助将不胜感激。
编辑: 好吧,因为这显然是一个开放的错误,我做了一个愚蠢的修复,并让它像这样工作:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.First();
for (int i = 0; i < user.l1.l2.Count; i++)
{
user.l1.l2[i].l3 = context.l3DB
.Where(p => p.l2.Id == user.l1.l2[i].Id)
.ToList();
}
为了让它起作用,我在 类 中添加了引用(到 parents)。 例如:
public class ClassL2 {
public List<ClassL3> l3 { get; set; }
public ClassL1 l1 { get; set; }//reference to parent
}
检查这个:
user = context.Users
.Where(u => u.UserName == model.Username)
.Include(u => u.l1)
.ThenInclude(l1 => l1.l2)
.ThenInclude(l2 => l2.l3)
.First();
这个怎么样:
user = (from usr in context.Users
where usr.UserName == model.Username
select new
{
usr,
usr.l1,
l2List = from l2 in usr.l1.l2
select new
{
l2,
l2.l3
}
}).AsEnumerable().Select(m => m.usr).First();