c#-4.0 - Entity Framework - Code First 不加载引用的对象

标签 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; }
    ...
}

在数据库中保存 Company 后,我有 Company (Id = 1 | name = "blah"| AddressId = 1) 及其地址 (Id = 1, Country = "Poland")。当我尝试从我的 DbContext 加载时:
Company company = context.Companies.Find(id);

我得到了空地址属性的公司。我究竟做错了什么?

(我正在使用 CTP5。)

最佳答案

尝试这个:

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

或使用新的类型语法:
Company company = context.Companies.Include(c => c.Address).Find(id);

这告诉 EF 急切地加载 Address实体作为您的一部分 Company实体。

似乎您在 EF 之上还有存储库层 - 确保您的存储库实现支持 Include()如果是这样的话。

对于初学者来说,这是 Include() 的实现Julia Lerman 在“Programming Entity Framework”中提供的支持带有 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;
}

关于c#-4.0 - Entity Framework - Code First 不加载引用的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5385248/

相关文章:

c# - t4 "using"关键字

entity-framework - Entity Framework 事务和sql azure默认隔离级别

entity-framework - 使用EF4选择

.net - 如何使用asp .net web api、 Entity Framework 和json(代码优先)来回带关系的对象?

asp.net - 内存转储不显示 IIS 崩溃的详细信息

javascript - 无法从静态方法运行 Javascript

entity-framework - C# 在 EntityFramework 中删除多个集合的最佳方法

linq - LInq 中的 Sum(AND(column))

entity-framework - 没有外键的 Entity Framework 代码优先映射

c# - 用FK关系向数据库插入数据