Search code examples
entity-frameworklinqiqueryable

Get value of dynamically chosen column


I have a POCO class describing my model:

public class Example
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

What I'm trying to do is an extension method to project my class this way using Entity Framework DbSets:

var qry = db.Examples.Select(x => new {
    Prop1 = x.Prop1,
    Prop2 = x.Prop2,
    Prop3 = x.Prop3,
    Description = XXXXX
}).ToList();

Where XXXXX is the value of the Prop1, Prop2 or Prop3 property, which name I know as an string only at runtime.

I cannot use Dynamic Linq, because I'm targeting Entity Framework Core, and I'm getting crazy with LINQ expressions and I think I'm still far from the solution... Could you provide some guidance, please?


Solution

  • As you fetch all needed properties for Description explicitly, you can fetch the query without Description and then generate the desired query from the loaded data.

    Assuming the name of the property for setting Description is stored in name variable:

    var qry1 = db.Examples.Select(x => new {
        Prop1 = x.Prop1,
        Prop2 = x.Prop2,
        Prop3 = x.Prop3,
    }).ToList();
    var qry = qry1.Select(x => new {
        Prop1 = x.Prop1,
        Prop2 = x.Prop2,
        Prop3 = x.Prop3,
        Description = name == "Prop1"? x.Prop1 : name == "Prop2"? x.Prop2: x.Prop3
    }).ToList();
    

    If you don't like hard coding the names, you can use reflection to get the value:

    Description = GetProp(x, name)
    

    where GetProp is:

    private string GetProp(object y, string name)
    {
       return y.GetType().GetProperty(name).GetValue(y).ToString();
    }