[英]LINQ query returning null for nested objects in Entity DB
I have a database I created using entity code first我首先使用实体代码创建了一个数据库
In that DB I have a structure similar to the following在那个数据库中,我有一个类似于以下的结构
class ClassA
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual ClassB B {get;set}
public virtual ClassC C {get;set}
...
}
class ClassB
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual string some_values {get;set}
...
}
class ClassC
{
public virtual int ID {get;set}
public virtual string some_text {get;set}
public virtual string some_values {get;set}
...
}
....
Finally I have a context for those objects with all of the interface to query the DB最后,我为那些具有所有接口的对象提供了一个上下文来查询数据库
public class ClassADb : DBContext, IClassADataSource
{
public DBSet<ClassA> As {get;set}
public DBSet<ClassB> Bs {get;set}
public DBSet<ClassC> Cs {get;set}
...
}
When I create the DB and explore it I can see that it was created what seems to be correctly:当我创建数据库并探索它时,我可以看到它的创建似乎是正确的:
In the ClassA_Table I see foreign keys for ClassB_ID, ClassC_ID, etc as well as all of the primitive types encapsulated in ClassA (ints, strings, bools, dates, etc)在 ClassA_Table 中,我看到 ClassB_ID、ClassC_ID 等的外键以及封装在 ClassA 中的所有原始类型(整数、字符串、布尔值、日期等)
Also when performing something along the lines of:同样在执行以下操作时:
ClassB MyB = new ClassB();
//some code to initialize B
...
Bs.Add(MyB)
ClassC MyC = new ClassC();
//some code to initialize C
Cs.Add(MyC);
ClassA MyA = new ClassA();
A.B = MyB;
A.C = MyC;
...
db.SaveChanges();
The Problem I am having is that when I do a select from As container , I can retrieve the A object but the nested B and C objects are null我遇到的问题是,当我从 As 容器中进行选择时,我可以检索 A 对象,但嵌套的 B 和 C 对象为空
The primitive types are OK (not empty)原始类型正常(非空)
Some fixes I tried我尝试过的一些修复
The virtual
keyword is lazy , so in the constructor of the class accessing the database i did virtual
关键字是惰性的,所以在访问数据库的类的构造函数中我做了
db.Configuration.ProxyCreationEnabled = false;
But still when doing something along the lines of但仍然在做一些事情时
A myA = db.As.Find(1);
A.some_text ; // not null
A.B ; //NULL!!!!
A.C ; // NULL
What is causing the entity framework not to fetch the A and B object?是什么导致实体框架不获取 A 和 B 对象?
You have to explicitly load related entities explicitly using Include()
.您必须使用
Include()
显式加载相关实体。
db.As.Include("B").Include("C").Where(a => [some condition]);
In newer version of the Entity Framework there is also a wrapper method around this method accepting a lambda expression avoiding the strings.在较新版本的实体框架中,此方法还有一个包装方法,该方法接受 lambda 表达式,避免使用字符串。
db.As.Include(a => a.B).Include(a => a.C).Where(a => [some condition]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.