预加载在 EF 中不起作用

发布于 2025-01-06 22:30:38 字数 726 浏览 2 评论 0原文

我正在拔头发,我不知道为什么我无法返回 AdPhotos 和 Location 实体。我正在使用 .ToList() 是否应该保持 AdPhotos 集合完好无损?

当我在返回上放置断点时,我可以看到 AdPhotos 和 Location 中的数据,但之后它就消失了。

public List<AdListing> LatestAdListings()
{
    using (var db = new AdultdirectoryEntities())
    {
        var results = (from a in db.AdListings.Include("AdPhotos").Include("Location")
                       join l in db.Locations on a.LocationID equals l.LocationID
                       where a.Approved && l.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0
                       orderby a.CreateDateTime descending
                       select a).Take(5).ToList();

        return results;
    }
}

I am pulling out my hair, I have no idea why I can't return the AdPhotos and Location entities. I am using .ToList() shouldn't it keep the AdPhotos collection intact?

When I place a breakpoint on the return, I can see the data in AdPhotos and Location but after that it disappears.

public List<AdListing> LatestAdListings()
{
    using (var db = new AdultdirectoryEntities())
    {
        var results = (from a in db.AdListings.Include("AdPhotos").Include("Location")
                       join l in db.Locations on a.LocationID equals l.LocationID
                       where a.Approved && l.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0
                       orderby a.CreateDateTime descending
                       select a).Take(5).ToList();

        return results;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

彩虹直至黑白 2025-01-13 22:30:38

您的 Include 调用之后是手动加入 - 不支持这种方式。一旦您使用手动连接或投影,您就会改变查询的形状,并且所有 Include 调用都会丢失。

此外,您不需要联接,因为您可以编写如下查询:

var results = (from a in db.AdListings.Include("AdPhotos").Include("Location")
               where a.Approved && a.Location.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0
               orderby a.CreateDateTime descending
               select a).Take(5).ToList();

Your Include call is followed by manual join - that is not supported. Once you use manual join or projection you are changing shape of the query and all Include calls are lost.

Moreover you don't need the join because you can write the query like:

var results = (from a in db.AdListings.Include("AdPhotos").Include("Location")
               where a.Approved && a.Location.CountryID == Constants.ItemKeys.UsCountryId && a.AdPhotos.Count > 0
               orderby a.CreateDateTime descending
               select a).Take(5).ToList();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文