简体   繁体   中英

How to sort lazy-loaded entities, using entity framework?

I'm using Entity Framework's code-first method. I've got two entities, with a one to many relation between them.

My question, is there a way to configure a table to always sort a certain way, so that I do not have to explicitly say I want to sort by something in the query via an OrderBy ?

You can wrap your DbSet<T> as IQueryable<T>

public IQueryable<MyEntity> MyEntities
{
  get{ return this.Set<MyEntity>().OrderBy(t => t.Column); }
}

the only problem is that you will affect every single query from performance perspective even when is not necessary.

I'm not sure about reconfiguring the table, but you could always do something like that in your DbContext file. You could have an IQueryable of whatever type you're looking at which would return the corresponding DbSet except ordered exactly as you want it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM