max
max

Reputation: 55

Dynamically refer to Entity Framework columns in IQueryable<T>

I know that some similar question were wandering around stack overflow however though none of them seem to work the way I want to. Here's the idea what I want to achieve:

// arrays vary depends what's in bigger loop
string[] columnNames = {"id", "name", "surname", "address", "phone"} 

// ...

foreach (string columnName in columnNames)
{
    if (condition)
    {
        IQueryable<tableType> query = from x in dbContext where x.(**columnName**).contains(otherVariable) select x;
    }
    // ...
    // Another queries wrapped in if conditions
}

I've tried this with typeof() and Type.GetProperty() which I found here and it seems not be working whatsoever. Another thing is I want this to be as much as possible in standards with current best practices and if I'm looking into wrong direction then where should I point to? I need to get this sort of method reusable for tens of hundreds of views and tables.

cheers,

Upvotes: 2

Views: 1733

Answers (2)

max
max

Reputation: 55

I have to answer my question with link to another post answered by @Aleks Andreev

LINQ where condition with dynamic column

This is exactly what I was looking for.

Upvotes: 0

Holger
Holger

Reputation: 2654

Instead of storing strings in your array, you should store expressions.

Expression<Func<TableType, bool>>[] conditions = new {
    x => x.ID > 5,
    x => x.Name > "M" };

etc. Than you can query

var query = dbContext.YourTable.Where(conditions[1])

That's a little simpler and easy to read, than using reflection or dynamics or whatever.

You can combine multiple conditions also, by multiple where clauses.

Since your sample implied a where clause, I had to invent some boolean expressions here.

Just don't start with storing strings (unless these strings are entered by the user)

Upvotes: 1

Related Questions