强制急切加载导航属性

发布于 2024-11-06 06:44:37 字数 376 浏览 0 评论 0原文

我正在使用 EF Code First,并且有一个名为 Category 的导航属性,我希望在每次调用中都急切加载该属性:

public class Product
{
    ...
    public Category Category { get; set; }
}

为此,我必须将其包含在我将在 Product 上执行的每次调用中

var results = from p in db.Products.Include("Category") select p;

有没有办法让 Category 属性急切加载,因此在每次调用中生成一个 SQL 连接,而不必每次都包含它?

谢谢

I'm using EF Code First and I have a navigation property called Category that I want eager loaded in every call:

public class Product
{
    ...
    public Category Category { get; set; }
}

To do this I have to include it in every call I'll do on Product

var results = from p in db.Products.Include("Category") select p;

Is there a way to have Category property eager loaded, therefore generation a SQL join, in every call without having to include it every time?

thank you

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

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

发布评论

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

评论(2

疯了 2024-11-13 06:44:37

一种简单的方法是定义一个扩展方法

static class DbExtensions{
   public IQueryable<Product> ProductsWithCategories(this MyContext db) {
       return db.Products.Include("Category");
   }
}

,它允许您使用但

var results = from p in db.ProductsWithCategories() select p;

不确定它是否带来很多好处......

One simple way would be to define an extension method

static class DbExtensions{
   public IQueryable<Product> ProductsWithCategories(this MyContext db) {
       return db.Products.Include("Category");
   }
}

Which allows you to use

var results = from p in db.ProductsWithCategories() select p;

Not sure if it brings much benefit though...

维持三分热 2024-11-13 06:44:37

您可以使用 @jeroenh 提出的辅助方法,但它无法解决您想要加载所有订购产品及其类别的订单的情况。 EF 没有任何自动预先加载配置,例如 Linq-to-sql 中提供的配置。您必须始终使用 Include (直接使用或通过某些辅助构造)。

You can use helper method as proposed by @jeroenh but it will not solve situation where you for example want to load order with all ordered products and their categories. EF doesn't have any automatic eager loading configuration as for example available in Linq-to-sql. You must always use Include (either directly or by some helper construction).

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