Sorting data using EF DbSet [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
开发者_运维技巧 Improve this questionIs there a way to pass an order by clause to a DbSet class in EF?
I'm using C#
I am not sure how to do that from DbSet, but you can do this from DBContext by getting access to the IQueryable
private readonly DbContext context;
...
context.Set<T>().OrderBy(item => item.Property)
What about using .OrderBy
directly on the Entity?
db.Employees.OrderBy(p => p.Id);
Here db.Employees is a DBSet. Is that what you're trying to do?
using System.Linq;
namespace MyNamespace
{
public class MyClass
{
public DBContext db;
public void MyMethod
{
foreach (var emp in db
.Employees
.Where(e => e.IsActive) // (or whatever)
.OrderBy(e => e.LastName))
{
DoSomething(emp);
}
}
}
}
As mentioned by Alexandre you can do that in query like:
var emps = from e in _db.Employees
orderby e.FirstName
select e;
Here _db.Employees is DbSet.
this would have to be done in a query,
or you would need to define a QueryView in the Edmx.
a QueryView can be used to specify / order / filter the data.
Have a look at this : DefiningQuery versus QueryView
using System.Data.Entity;
using System.Linq;
var items = DataContext.Employees.OrderBy(x=> x.Name).ToList();
Or, for async:
var items = await DataContext.Employees.OrderBy(x=> x.Name).ToListAsync();
精彩评论