Reputation: 8772
Is there a way to pass an order by clause to a DbSet class in EF?
I'm using C#
Upvotes: 10
Views: 23720
Reputation: 105
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();
Upvotes: 1
Reputation: 7276
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.
Upvotes: 2
Reputation: 7545
What about using .OrderBy
directly on the Entity?
db.Employees.OrderBy(p => p.Id);
Upvotes: 4
Reputation: 4341
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);
}
}
}
}
Upvotes: 3
Reputation: 35925
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)
Upvotes: 22
Reputation: 6753
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
Upvotes: 1