Linq Queries abstraction with expressions, which way is better?

We’ve been looking for a nice approach to querying our database, focusing on both ease of development, readability and business rules compliance.

I’ve found two interesting articles on the internet that describe similar but slightly different approaches, one is using a Query Object and Expressions, and the other is using mainly extension methods with business relevant intentions and ultimately expressions as well.

Query Object approach : https://lostechies.com/chadmyers/2008/08/02/query-objects-with-repository-pattern-part-2/

Extension Method approach : https://www.simple-talk.com/dotnet/.net-framework/giving-clarity-to-linq-queries-by-extending-expressions/

Here’s some example code that we could have (inside the repository) for both cases:

public IEnumerable<ControlOverview> GetRoutineControlOverviewsForTest(string testId, DateTime dateOfInterest)
    {
        var controlOverviewQuery = new ControlOverviewQuery().ForTest(testId)
                                                             .ForLotUsage(ControlLotUsageStatus.Routine)
                                                             .ForControlStatusAt(dateOfInterest)
                                                             .ForControlConfigurationAt(dateOfInterest)
                                                             .ForControlLotConfigurableAt(dateOfInterest);

        return this.Context.ControlOverviews.Where(controlOverviewQuery.AsExpression());;
    }

second case:

public IEnumerable<ControlOverview> GetRoutineControlOverviewsForTest(string testId, DateTime dateOfInterest)
    {
        return this.Context.ControlOverviews.ForTest(testId)
                                            .ForLotUsage(ControlLotUsageStatus.Routine)
                                            .ForControlStatusAt(dateOfInterest)
                                            .ForControlConfigurationAt(dateOfInterest)
                                            .ForControlLotConfigurableAt(dateOfInterest);
    }

As you can see, from the developer perspective it’s more or less the same. Same for readibility. The only thing that is different is the implementation detail (extension methods vs query object)

In my team there are divided opinions on using one or the other, and I can’t find a good set of arguments (pros/cons) to go in favour of one approach or the other.

I personally prefer the first approach (query object), since i’m OOP guy and like the builder pattern that it uses, but I cannot find a better argument than that in order to not use extension methods.
I’d highly appreciate some insight here. Perhaps this is just a coding preference and it’s difficult or just not possible to say that one is certainly better than the other with a strong argument

Thanks


Source: .net

Leave a Reply