Sorting data using EF DbSet [closed]
Asked Answered
C

6

10

Is there a way to pass an order by clause to a DbSet class in EF?

I'm using C#

Cryptology answered 20/5, 2011 at 15:37 Comment(0)
A
22

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)
Acquaintance answered 20/5, 2011 at 16:5 Comment(1)
I know this is not exactly what I asked, but it does the job right there in the viewCryptology
H
4

What about using .OrderBy directly on the Entity?

db.Employees.OrderBy(p => p.Id);
Hood answered 11/7, 2014 at 4:32 Comment(0)
C
3

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);
            }
        }
    }
}
Champac answered 29/10, 2013 at 13:53 Comment(0)
P
2

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.

Pundit answered 20/5, 2011 at 16:0 Comment(0)
A
1

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

Auer answered 20/5, 2011 at 15:41 Comment(1)
you can consume an EDMX from code first, but then again it kinda defies the whole code first concept.Auer
C
1
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();
Cartesian answered 13/10, 2018 at 14:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.