S
S
stcmd042362016-05-26 14:09:06
Entity Framework
stcmd04236, 2016-05-26 14:09:06

How to dynamically generate conditions in Entity Framewrok?

How can I dynamically generate query conditions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maa-Kut, 2016-05-26
@stcmd04236

Yes, just throw them to IQueryable:

IQueryable<Person> query = context.Persons;

if (searchByFirstName)
    query = query.Where(x => x.FirstName == someFirstName);

if (searchByAge)
    query = query.Where(x => x.Age == someAge);

var persons = query.ToList();

When generating an SQL query, all these separate conditions will be collected into one beautiful WHERE.
Another option is to build Linq Expressions. The method is more flexible, but more complex. For example, you can read it here: https://msdn.microsoft.com/en-us/library/mt654267.aspx.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question