2

I have a form where the user selects a property that ends up getting used in a query. Since I don't know what that property will be, my query has to do it 'dynamically' so I wrote the following code in hopes of not having to write a ton of if/else statements since MyType has a ton of properties

MyType content = null;
foreach (var prop in typeof(MyType).GetProperties())
{
    if (userProperty == prop.Name)
    {    
        content = db.MyType.Where(mt =>
            mt.GetType().GetProperty(prop.Name)
            .GetValue(mt).ToString() == someOtherValue)
        .FirstOrDefault();
        break;
    }
}

which results in

Exception thrown: 'System.NotSupportedException' in EntityFramework.SqlServer.dll

After a bit of research I learned this is because the Entity framework does not support the use of all methods within its query builder methods. Ok, So I think to myself that I just need to store the fetched property value in a variable first and then just plug that into the Where query.....but how would I do this? I obviously can't declare a variable within the Where method, but it's only in the context of the Where method that I can get a hold on my value.

At this point I see myself having two options.

  1. Bite the bullet and just write a ton (like 35) of if/else statements with duplicate code in them
  2. Fetch all of the MyType content from the database as a List and then have freedom

Option one is unappealing for obvious reasons, and option two just seems extremely inefficient to me as there is a huge amount of data in the database and I only need one row of it.

So....what can I do? I know there has to be a way to accomplish this how I want, but I just don't know how.

secondbreakfast
  • 4,194
  • 5
  • 47
  • 101
  • Use linqkit and pass in the predicate to the where clause. You'll still have a bunch of if statements, but you'll only have one linq statement at the end – Steven Ackley Dec 14 '15 at 15:17
  • check out these answers. http://stackoverflow.com/questions/9505189/dynamically-generate-linq-queries – JamieD77 Dec 14 '15 at 15:51

0 Answers0