EF 4.1 - 将项目添加到虚拟的集合属性中
我首先使用 EF 4.1 代码。给出以下类片段:
public class Doctor
{
public virtual ICollection<Hospital> Hospitals { get; set; }
}
注意:我在数据库上下文中有这个:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
this.Configuration.LazyLoadingEnabled = false;
}
我想确保这里不涉及延迟加载。
我遇到的问题是,如果 Hospitals 属性上没有 virtual
关键字,当我检索一位确实有与其关联的医院的医生时,该集合为空。 通过包含 virtual
关键字,hospitals 集合确实包含 1 个项目,这正是我所期望的。
问题是,当我想创建一个全新的医生并立即将他与医院关联时,我会得到一个 Null reference
异常,因为 Hospitals 属性尚未初始化。
有人可以指出我在这里做错了什么吗?创建新医生时如何向医院添加项目。
干杯。 贾斯。
I'm using EF 4.1 code first. Given the following class snippet:
public class Doctor
{
public virtual ICollection<Hospital> Hospitals { get; set; }
}
Note: I have this in the database context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
this.Configuration.LazyLoadingEnabled = false;
}
I wanted to make sure that lazy loading is not involved here.
The issue I have is that, without the virtual
keyword on the Hospitals property, when I retrieve a doctor that does have a hospital associated with him, the collection is empty.
By including the virtual
keyword, the hospitals collection does contain 1 item, which is what I expect.
The problem is that, when I want to create a brand new doctor and associate him with a hospital immediately, I get a Null reference
exception, since the Hospitals property has not been initialised yet.
Can someone point out what I'm doing wrong here? How can I add items to the Hospitals upon creating a new doctor.
Cheers.
Jas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码与您通常在所有示例中看到的代码相同,但为了使这项工作正常进行,此代码要好得多:
如果您不使用
virtual
关键字,EF 将不会为您初始化集合。同时,如果您通过其构造函数创建全新的Doctor
,则必须自己处理初始化。Your code is something what you usually see in all examples but to make this work this one is much better:
If you don't use
virtual
keyword EF will not initialize collection for you. In the same time if you create brand newDoctor
via its constructor you must handle initialization yourselves.我想这可以帮助你。
I think this can help you.