Given the following LINQ statement, can someone tell me if it is possible to refactor the select portion into an expression tree? I have not used expression tree's before and have not been able to find much information regarding Selects.. Note this is to be translated into SQL and run inside SQL Server, not in memory.
var results = db.Widgets
.Select(w => new
{
Name = (w is x) ? "Widget A" : "Widget B"
});
I would like to be able to do this..
var name = [INSERT REUSABLE EXPRESSION]
var somethingElse = [INSERT REUSABLE EXPRESSION]
var results = db.Widgets.Select(w => new { Name = name, SomethingElse = somethingElse });
Obviously the intended use is for more complex statements.
You can do this using LinqKit. It'll work as long as your method is translatable to SQL. This is essentially what a complete example might look like:
public static class ReusableMethods
{
public static Expression<Func<int, Person>> GetAge()
{
return p => p.Age;
}
}
var getAge = ReusableMethods.GetAge();
var ageQuery = from p in People.AsExpandable()
select getAge.Invoke(p);
Note that:
AsExpandable() to your IQueryable.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With