简体   繁体   中英

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,

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM