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

发布于 2024-10-24 12:09:25 字数 545 浏览 1 评论 0原文

我首先由代码生成两个简单的类。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苦妄 2024-10-31 12:09:25

试试这个:

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;
}

try this:

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

or with the new typed syntax:

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

This tells EF to eagerly load the Address entity as part of your Company 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):

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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文