Entity framework EF 6.1.1上的奇怪加载行为
我做了一个简单的例子来检查EF延迟加载行为,发现了一些非常奇怪的事情。我的例子如下:Entity framework EF 6.1.1上的奇怪加载行为,entity-framework,lazy-loading,Entity Framework,Lazy Loading,我做了一个简单的例子来检查EF延迟加载行为,发现了一些非常奇怪的事情。我的例子如下: class Foo { public int Id {get;set;} public string Name {get;set;} public virtual ICollection<Bar> Bars {get;set;} } class Bar { public int Id {get;set;} public string Name {get;se
class Foo
{
public int Id {get;set;}
public string Name {get;set;}
public virtual ICollection<Bar> Bars {get;set;}
}
class Bar
{
public int Id {get;set;}
public string Name {get;set;}
public int FooID {get;set;}
[ForeignKey("FooID")]
public virtual Foo Foo {get;set;}
}
class Context : DbContext
{
public DbSet<Foo> Foo {get;set;}
public DbSet<Bar> Bar {get;set;}
}
class Demo
{
static void Main(string[] args)
{
Context ctx = new Context();
var foos = ctx.Foo.ToList();
var bars = ctx.Bar.ToList();
Console.ReadLine();
}
}
懒洋洋的工作做得很好
但如果我只运行其中一条线路:
var foos = ctx.Foo.ToList();
//var bars = ctx.Bar.ToList();
或
在这种情况下,延迟加载不起作用,我只在bar
或Foo
属性中得到null
。有人能解释一下这里发生了什么事吗
编辑
笨拙的我,原来发生这种行为是因为我没有将
public
修饰符添加到Foo
和Bar
的类定义中,您不知道延迟加载是什么
延迟加载发生在
- 从数据库加载实体(不包括相关实体)
- 当您仍在上下文中时,可以访问它的一个导航属性。此时,上下文将查询数据库以填充导航属性
public class Parent
{
public int ParentId { get; set; }
public virtual ICollecton<Child> Children { get; set; }
}
您可以从数据库中获得一个父对象,而不包含其子对象。此时,如果尚未处理上下文,则可以执行以下操作:
foreach(var child in parent.Children)
如果这是您第一次访问Children
属性,则上下文将查询数据库并填充它。这是延迟加载。任何其他事情,它不是懒惰加载
请阅读本文以了解加载相关实体的所有可能方式(急切、明确或懒惰):
这是应该的。“延迟加载是指第一次访问引用实体的属性时自动从数据库加载实体或实体集合的过程。”您需要显式访问属性才能加载它。
public class Parent
{
public int ParentId { get; set; }
public virtual ICollecton<Child> Children { get; set; }
}
var parent = myContext.Parents.First()
foreach(var child in parent.Children)