【问题标题】:Can Entity Framework sort entities by properties on a related entity?Entity Framework 可以按相关实体上的属性对实体进行排序吗?
【发布时间】:2012-12-08 15:13:32
【问题描述】:

假设我有以下“Foo”和“Bar”实体:

class Foo {
   int FooId;
   string FooName;
}

class Bar {
   int BarId;
   Foo RelatedFoo;
   string BarName;
}

我们还假设我希望默认情况下延迟加载“RelatedFoo”。

在实体框架中,是否可以执行返回可枚举的“Bar”实体的查询,其中元素按“bar.RelatedFoo.FooName”排序?

如果是这样,这可以在固定数量的数据库查询中完成吗?我想避免这样做N+1 queries

如果不是,这是否可以在另一个 .NET ORM 框架中实现?

【问题讨论】:

    标签: entity-framework orm


    【解决方案1】:
    var bars = _context.Bars.OrderBy(b => b.RealtedFoo.FooName)
    

    您可能还想只带回RealtedFoo 不为空的那些条

    var bars = _context.Bars.Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName)
    

    更新:

        //For EF only
        _context.Configuration.LazyLoadingEnabled = false
    
        //If you want to bring back RealtedFoo then include it. 
    //Otherwise, you can just query for it and not use the Include() extension.
        var bars = _context.Bars.Include(b => b.RealtedFoo).Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName)
    

    【讨论】:

    • 我不确定实际查询在 SQL Server 中会是什么样子,但您可以运行 SQL 分析器来查看。你问的是这个吗?
    • 我想确保我不会通过访问 RelatedFoo 进行 N 次查询。
    • 这也取决于你是在实体框架中使用 Eager 还是 Lazy Loading。
    • 假设我正在使用延迟加载。不进行 N 次查询(其中 N 是条形对象的数量)就可以做到这一点?
    • 我不确定你在问什么。这一行将带回 RealtedFoo 不是 NUll(第二个表达式)的所有 Bars(在您的数据库中),并按 FooName 对它们进行排序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多