Entity Framework - LINQ - Dynamic Column Names

c# entity-framework-6 lambda linq

Question

I know that this question was asked several times but the more answers I came accross the more I got confused.

Given I have a table Categories and within this table columns: Category1, Category2, Category3 and so on.. How can I write a method like below and use a parameter (in this case catno)

As simplified as I could get;

public List<string> GetProductCategories(int catno)
{
    using (var ctx = new myEntities())
    {
        return (from c in ctx.Categories
                select c.Category1).ToList();
               //1 being the catno parameter obviously
    }
}

I definitely DO NOT want to use the Dynamic Linq library as it is not type safe. And although (and obviously) a working answer would do fine, a detailed explanation to the problem and the solution is provided.

Thanks in advance

1
0
10/11/2018 10:17:43 AM

Popular Answer

You can define expression that selects the property based on string name. Then in IQueryable interface you can use it in Select argument. You would need to use method syntax for it though:

public List<string> GetProductCategories(int catno)
{
    var parameter = Expression.Parameter(typeof(Category));
    var property = Expression.Property(parameter, $"Category{catno}");
    var selector = Expression.Lambda<Func<Category, string>>(property, parameter);

    using (var ctx = new myEntities())
    {
        return ctx.Categories
            .Select(selector)
            .ToList();
    }
}

Expression.Property method is performing some type checks so if on type Category there is no given property defined it will thrown an excpetion. For example this will fail if there is no Category0 property:

var property = Expression.Property(parameter, "Category0");
0
10/11/2018 12:36:15 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow