实体框架可以通过相关实体的属性对实体进行排序吗? [英] Can Entity Framework sort entities by properties on a related entity?
问题描述
假设我有以下Foo和Bar实体:
class Foo {
int FooId ;
string FooName;
}
class Bar {
int BarId;
Foo RelatedFoo;
string BarName;
}
我们还假设我希望RelatedFoo默认为延迟加载
在实体框架中,是否可以执行一个查询,返回一个枚举的Bar实体,其中元素按bar.RelatedFoo.FooName排序? / p>
如果是这样,这可以在固定数量的数据库查询中完成吗?我想避免执行 N + 1个查询。
如果没有,这是否可能在另一个.NET ORM框架中?
var bars = _context.Bars.OrderBy(b => b.RealtedFoo.FooName)
您可能还只想带回那些 RealtedFoo
不为空的栏
var bars = _context.Bars.Where(b => b.RelatedFoo!= null).OrderBy(b => b.RealtedFoo.FooName)
更新:
//对于EF只有
_context.Configuration.LazyLoadingEnabled = false
//如果你想带回RealtedFoo,然后包含它。
//否则,您只能查询它,而不使用Include()扩展名。
var bars = _context.Bars.Include(b => b.RealtedFoo).Where(b => b.RelatedFoo!= null).OrderBy(b => b.RealtedFoo.FooName)
Suppose I have the following "Foo" and "Bar" entities:
class Foo {
int FooId;
string FooName;
}
class Bar {
int BarId;
Foo RelatedFoo;
string BarName;
}
Let's also suppose that I want "RelatedFoo" to be lazy-loaded by default.
In Entity Framework, is it possible to do a query that returns an enumerable of "Bar" entities where elements are sorted by "bar.RelatedFoo.FooName"?
If so, can this be done in a fixed number of database queries? I would like to avoid doing N+1 queries.
If not, is this possible in another .NET ORM framework?
var bars = _context.Bars.OrderBy(b => b.RealtedFoo.FooName)
You may also want to only bring back those bars that RealtedFoo
is not null
var bars = _context.Bars.Where(b => b.RelatedFoo != null).OrderBy(b => b.RealtedFoo.FooName)
Update:
//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)
这篇关于实体框架可以通过相关实体的属性对实体进行排序吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!