Turo
Turo

Reputation: 1607

Dynamic linq query with join

Here is my try of dynamic Linq query with join. I try to get list of unique categories, brands and other criteria which were present in last reading in database. What is passed to the query (brand, category etc.) would only be defined at runtime.

I read about best way of doing this with func's, predicates etc., I think this is beyond my capacity at this stage. I'm trying the easier way with query string, which I got working for some simpler case, but I'm doing something wrong here with join. If I do just plain select product.Category with intellisense of course this works, but not in string in select clause.

  public IEnumerable<string> getFilterItems(string dbColumn)
    {
        var filterItems = new List<string>();

        return (from reading in Helper.LatestReadings
                where reading.Distributor != Helper.Client
                join product in Helper.Context.Products
                       on reading.ProductId equals product.SkuCode
                select ("product." + dbColumn)).Distinct();
    }

Upvotes: 0

Views: 1059

Answers (2)

Viru
Viru

Reputation: 2246

you can use reflection to achieve this

public IEnumerable<string> getFilterItems(string dbColumn)
    {
        var filterItems = new List<string>();

        var productList = from reading in Helper.LatestReadings
                where reading.Distributor != Helper.Client
                join product in Helper.Context.Products
                       on reading.ProductId equals product.SkuCode
                select product;
         return productList.Select(x=>x.GetType().GetProperty(dbColumn).GetValue(x)).Cast<string>().Distinct();
}

Upvotes: 1

Markus Weninger
Markus Weninger

Reputation: 12648

"product." + dbColumn evaluates to a String, therefore select ("product." + dbColumn) will return this string n times, one time per item in the result of your query.

This SO question has an answer if you want to have a dynamic select. It proposes a method so that you could write something like

var result = list.Select( CreateNewStatement( "Field1, Field2" ) );


EDIT: Oh, sorry, I just read about "dynamic LINQ" here, therefore my above answer may not be that helpful. As I can see on the linked page, they use the following format in Select.

.Select("new(<ColumnName> as <DataMemberName>, ... )");

In your case you should try

.Select("new(product" + dbColumn + " as Value)");

Upvotes: 0

Related Questions