LINQ to SQL, the Specification Pattern and Dynamic Queries
A while back Udi posted on Fetching Strategies that he implemented with NHibernate. I have just finished working on an implementation of the Specification Pattern that will work with LINQ (to objects) using Lambdas to provide the test logic and in the case of LINQ to SQL using the same testing predicates as search predicates when querying the database.
1: public static void SpecForLambdaWithDatabase()
2: {
3: Specification<Customer> coNameSpec =
4: new Specification<Customer>
5: (c => c.CompanyName == “Blauer See Delikatessen”);
6:
7: NorthwindDataContext ctx = new NorthwindDataContext();
8:
9: //TODO: Turn this into a fetching strategy that
10: //can be loaded when a Repository method is called
11: //using a role. Dependancy Injection will be useful
12: //in allowing us slot in different fetching strategies
13: //over time if required.
14: DataLoadOptions options = new DataLoadOptions();
15: options.LoadWith<Customer>(c => c.Orders);
16: options.LoadWith<Order>(o => o.OrderLines);
17: ctx.LoadOptions = options;
18:
19: //Note: the specification passes it’s EvalPredicate
20: //as a Func<T,bool> argument to the ‘Where’
21: //extension method
22: var exp = from c in ctx.Customers
23: .Where<Customer>(coNameSpec.EvalPredicate)
24: select c;
25:
26: foreach(var c in exp)
27: {
28: Console.WriteLine(“The Customer ID ‘{0}’ “ +
29: “AND NAME ‘{1}’”,
30: c.CustomerID, c.CompanyName);
31: }
32: }
My next goal is to enable the eager and lazy loading in these scenarios dealt with by using something similar to Fetching Strategies and have the Repository load them using dependency injection which will enable me to plug in the correct fetching strategy at will.
Shortly I will post some code that demonstrates all this with a Repository and not the standard .DBML file, DataContext way of doing things as per above.


