Recent articles About

Compiling enterprise

Ivan Koshelev blog on software development

Articles for tags 'expression tree' Expression trees and advanced queries in C# 03 Expression Tree modification [2017 May 28] .NET, C#, IQueryable, Expression Tree, Expression Visitor

In part 1 we learned that you can swap parts of an Expression Tree to another compatible (i.e. with a matching return type) expression. Swapping is, in fact, the easiest thing to do - with a bit more work we can construct a serializable representation of almost any bit of C# code. This opens great avenues for Domain Driven Development and introducing hot-swappable, dynamic, yet safe parts of logic to your application.

One of the best examples of the power we get is shown by introducing a reusable expression function with LINQKit.

internal static class AddressSubqueries
{
internal static Expression<Func<string, string, string>> FormatCityAndProvince =
    (city, province) => "The glorious city of " + city 
                            + " of the wonderful province of " + province;
}
     
//used like this:
public IQueryable<string> GetStandardAddressDescription(int addressId)
{
    return DataContext
                .Addresses.AsExpandable() // this hooks in LINQKit 
                .Where(x => x.AddressId == addressId)
                .Join(
                    DataContext.StateProvinces,
                    adr => adr.StateProvinceId,
                    prov => prov.StateProvinceId,
                    (adr, prov) => AddressSubqueries.
                                        FormatCityAndProvince // <==
                                            .Invoke(adr.City, prov.Name))
                .FirstOrDefault();
}
continue reading
Ivan Koshelev photo

I'm passionate for anything that can be programed and automated to make life better for all of us.

Archives

  1. January 2023 (1)
  2. January 2022 (2)
  3. November 2021 (1)
  4. May 2021 (1)
  5. March 2020 (1)
  6. August 2019 (1)
  7. July 2019 (1)
  8. May 2019 (1)
  9. February 2019 (1)
  10. October 2017 (1)
  11. August 2017 (3)
  12. July 2017 (3)
  13. May 2017 (3)

Elsewhere

  1. GitHub@IKoshelev
  2. LinkedIn
  3. NuGet@IKoshelev
  4. NPM@IKoshelev