[英]Entity Framework 6 - lazy loading not working
This is my first time using EF. 这是我第一次使用EF。 As such I may have missed something simple that is preventing lazy loading of my BClass.
因此,我可能错过了一些防止延迟加载BClass的简单方法。 When I load AClass the 'B' property is null.
当我加载AClass时,“ B”属性为null。 I would have expected it to be populated as persisted.
我本来希望它能持久存在。
For my example I have two simple classes: 对于我的示例,我有两个简单的类:
public class AClass
{
public AClass()
{
Id = Guid.NewGuid();
B = new BClass();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public string Name { get; set; }
public virtual BClass B { get; set; }
}
public class BClass
{
public BClass()
{
Id = Guid.NewGuid();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public Guid Id { get; set; }
public string Description { get; set; }
}
In the 'Context' class: 在“上下文”类中:
public DbSet<AClass> AClasses { get; set; }
public DbSet<BClass> BClasses { get; set; }
Below is a simple test. 下面是一个简单的测试。 I was expecting xB would be loaded.
我期望xB将被加载。 Instead it is null?
相反,它为null?
using (var db = new TestContext())
{
AClass a = new AClass();
a.Name = "AClass";
a.B.Description = "BClass Description Goes Here!";
db.AClasses.Add(a);
db.SaveChanges(); // Works. Confirmed both a and a.B are persisted to the database
}
using (var db = new TestContext())
{
AClass x = db.AClasses.Where(a => a.Name == "AClass").FirstOrDefault();
System.Console.WriteLine(x.Name);
System.Console.WriteLine(x.B.Description); // x.B is null. Expected it to load and the .Description property to be "BClass Description Goes Here!"
}
Changes were persisted to the database correctly. 更改已正确保存到数据库中。 I can't post the screen shot yet.
我还不能发布屏幕截图。
From AClass table: 从AClass表中:
Id Name B_Id B7937E1B-9CC0-4318-B179-0D54B23B6CDA AClass 560D066B-4848-454D-B92C-F6AE4232057E
From BClass table: 从BClass表:
Id Description 560D066B-4848-454D-B92C-F6AE4232057E BClass Description Goes Here!
Entity Framework Version: 6.0.0.0 实体框架版本:6.0.0.0
Remove B
initialization form class AClass
: 删除
B
初始化表单类AClass
:
public AClass()
{
Id = Guid.NewGuid();
//B = new BClass();
}
The initialization causes the entity framework think that you assigned new value to B property of AClass
and does not assign it with a proxy. 初始化导致实体框架认为您
AClass
新值分配给AClass
B属性,而不是使用代理分配它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.