实体框架 - Code First不加载引用的对象

时间:2011-03-22 00:12:24

标签: c#-4.0 entity-framework-4 code-first ef-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。)

1 个答案:

答案 0 :(得分:5)

试试这个:

Company company = context.Companies.Include("Address").Find(id);

或使用新的类型语法:

Company company = context.Companies.Include(c => c.Address).Find(id);

这告诉EF热切地将Address实体加载为Company实体的一部分。

您似乎还在EF上安装了存储库层 - 如果是这种情况,请确保您的存储库实现支持Include()

对于初学者来说,这是Julia Lerman在“编程实体框架”中提供的Include()的实现,以支持使用POCOS的单元可测试存储库模式(此版本仅适用于第一种语法):

public static IQueryable<TSource> Include<TSource>(this IQueryable<TSource> source, string path)
{
    var objectQuery = source as ObjectQuery<TSource>;
    if (objectQuery != null)
    {
        return objectQuery.Include(path);
    }
    return source;
}