实体框架 - Code First 不加载引用的对象
我首先由代码生成两个简单的类。
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Country { get; set; }
...
}
将公司保存到数据库后,我有公司(Id = 1 | name =“blah”| AddressId = 1)及其地址(Id = 1,Country =“Poland”)。当我尝试从 DbContext 加载时:
Company company = context.Companies.Find(id);
我得到了 null Address 属性的公司。我做错了什么?
(我正在使用 CTP5。)
I have two simple classes generated by code first.
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public int Id { get; set; }
public string Country { get; set; }
...
}
After saving Company in database I have Company (Id = 1 | name = "blah" | AddressId = 1) and its Address (Id = 1, Country = "Poland"). When I'm trying to load from my DbContext:
Company company = context.Companies.Find(id);
I get company with null Address property. What am I doing wrong?
(I'm using CTP5.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
或者使用新的类型语法:
这告诉 EF 立即加载
Address
实体作为Company
实体的一部分。似乎您在 EF 之上有存储库层 - 如果是这种情况,请确保您的存储库实现支持
Include()
。对于初学者来说,这是 Julia Lerman 在“编程实体框架”中提供的
Include()
实现,用于支持 POCOS 的可单元测试存储库模式(此版本仅适用于第一种语法):try this:
or with the new typed syntax:
This tells EF to eagerly load the
Address
entity as part of yourCompany
entity.It also seems you have repository layer on top of EF - make sure that your repository implementation supports
Include()
if that's the case.Just for starters this is the implementation of
Include()
that Julia Lerman provides in "Programming Entity Framework" to support a unit-testable Repository pattern with POCOS (this version only works with the first syntax):