问题描述
大家好.我正在与Entity Framework进行一些讨论,但他不想接受失败!所以我会寻求帮助.
我将使用两个简单的实体作为示例:
Hi Everyone.. I''m having a little discussion with Entity Framework, but he doesn''t want to accept defeat! So I''ll ask for help..
I''ll use two simple entities as example:
public class parent{
int parentid {get;set;}
public ICollection<child> children{get; set;}
}
public class child{
int childid{get;Set;}
public virtual parent parent{get;set;}
}
现在有以下功能:
now the following function:
public ActionResult Edit(int id)
{
parent loadedParent = db.parent.Find(id);
ViewBag.childrenCount = parent.children.Count; /*Example instruction that generates Null reference exception*/
return(loadedParent);
}
如果我尝试以任何方式访问子级的Icollection,它将为我提供null引用异常.如果在父"类定义中,我将ICollection< child>设置为到虚拟,一切正常.
我在创建子代之前尝试将子代添加到父代时遇到了类似的问题.我认为,如果从数据库中进行拾取,则ICollection将充满相应的子代.
如果我没看错,那么virtual关键字应该只为指定实体启用lazyload;删除虚拟,从数据库中选择父对象时,EF是否不应该自动加载子对象?是否必须指定要同时加载子项和父项?
预先谢谢你,
Alberto
If I try to access, in any way, the Icollection of children, it gives me a null reference exception. If, in the "parent" class definition, I set the ICollection<child> to virtual, everything works fine.
I encountered a similar problem trying to add children to a parent before creating it.. I thought that, if picking up from the db, the ICollection would be filled with respective children.
If I''m not wrong, the virtual keyword should just enable lazyload for the specified entitites; removing virtual, shouldn''t EF automatically load children when picking parent from db? do I have to specify that I want to load also the children along with the parent?
thank you in advance,
Alberto
推荐答案
parent loadedParent = db.parent.include("children").FirstOrDefault(m=>m.parentid == id);
ViewBag.childrenCount = parent.children.Count;
return(loadedParent);
请注意,可以手动关闭惰性加载,并且我还阅读到在某些情况下,EF会自动将其关闭(如果我没记错,例如在模型验证期间进行验证).
Note that lazy loading may be manually turned off, and I have also read that in some cases EF will turn out it automatically (IF I''m not wrong, for examplte during model validation).
这篇关于与“非虚拟"问题有关. ICollections的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!