Home > Mobile >  Add a where clause to context.Set<T> in EntityFrameworkCore
Add a where clause to context.Set<T> in EntityFrameworkCore

Time:11-05

in aspnet core EntityFrameworkCore I'm developing a generic class to handle db operations and I have a Read() method that retrieves data from db like this:

            using (MyDbContext context = new MyDbContext())
            {
                var result = await context.Set<T>().ToListAsync();
                return result;
            }

Now I wold like to filter the data adding a where or something similiar, in order to be able to filter one or more Entitiy's properties, for exeample:

TypeId = 2

How can I get this?

CodePudding user response:

As Daniel mentioned in the comments, you need to use the Where extension method.

For example:

public async Task<List<T>> Read(Expression<Func<T, bool>> filter = null)
{
    using (MyDbContext context = new MyDbContext())
    {
        var result = context.Set<T>().AsQueryable();
        if (filter != null) result = result.Where(filter);
        return await result.ToListAsync();
    }
}

Entity Framework will convert the filter to a SQL query and perform the filtering in the database, rather than loading the entire set into memory before filtering it.

NB: This is a rather leaky abstraction. If you use any constructs in your filter parameter which aren't supported by Entity Framework, then you will get an exception at runtime.

  • Related