Living in the Tech Avalanche Generation

A practitioner’s introspective on technology
Archive for December 15th, 2008

Habits of the career minded programmer.

headphones One thing I often remark is my preference for developers who exhibit habits that identify them as being ‘invested in their careers’. One such habit (in my humble opinion) is regular listening to pod casts however I should say that if a developer doesn’t listen to pod casts does not mean that they are not invested, perhaps they have other such ‘invested’ habits. Anyway, this post wasn’t meant to be a discussion of what are and aren’t the habits but rather a list of pod casts that I listen to and think are worth checking out if you weren’t aware of them previously.

THE LIST:

There was a compiled list of pod casts knocking around recently that is more complete (I will post a link when I can find it) but these are the ones I listen too regularly.

Share/Save/Bookmark

2 comments

More Entity Framework frustration [I want my Specification Pattern].

A while back I posted about LINQ To SQL and how to implement the specification pattern and fetching strategies with a IRepository. Since then you may have heard the announcements and followed the ensuing debate about the future of LINQ To SQL. On reflection I have since decided to explore EF as fully as possible and prepare for knowing it deeply, particularly as it promises to embody values such as support of POCO and Lazy Loading which are some of things I am not prepared to live without.

In the meantime I thought it was worth taking the same approach as I had with LINQ To SQL and see what was possible with respect to implementing the Specification Pattern in order to provide dynamic querying ability (minus the repository - for the moment only).

Let’s start with a given Entity Model:

ef_spec_model

I am not going to use much of this model for the purpose of this post but some time soon I will look at how to implement a Fetching Strategies with Entity Framework in a similar manner as that which I demonstrated with LINQ To SQL, but let’s move forward with the specification patterns for now.

So given my model has Orders which aggregate Order_Details and Orders may contain discontinued products I might hypothetically want to sum the total of my unfulfilled problem orders where they contain discontinued products. If I just whip out my specification library (built for LINQ’ish entity / object matching and LINQ To SQL dynamic querying) and I attempt to use it directly with the Entity Framework in this fashion, I get the same behaviour as I expected previously with the other technologies.

static void Main(string[] args)
{
    Specification<Order> order_spec =
        new Specification<Order>(o => o.Order_Details.All
            (od => od.Product is DiscontinuedProduct));

    using (var ctx = new NorthwindEntities())
    {
        ObjectQuery<Order> orders =
            (ObjectQuery<Order>)
            from o in ctx.Orders
                .Include(“Order_Details”)
                .Include(“Customer”)
            .Where(order_spec.EvalPredicate)
            select o;

        Console.WriteLine(orders.ToTraceString());

        try
        {
            foreach (var order in orders)
            {
                var sumup =
                    order.Order_Details.Sum
                    (od => od.Quantity * od.UnitPrice);
                Console.WriteLine(sumup.ToString());
            }
        }
        catch (ArgumentException argEx)
        {
            Console.WriteLine(argEx.Message);
        }
    }

    Console.ReadLine();
}

Ok, that’s great but now I want to try combining specifications which I can do by taking advantage of the operator overloading for OR and AND. Bam, crash it comes tumbling down.

Now its late and I am starting to get annoyed with the Entity Framework. As it turns out (as far as I can tell), LINQ to SQL is far more pliable in managing dynamic queries. Why? Well EF doesn’t play nice with Expression<T>, specifically Expression<Func<T>> etc. Errors arise when you build and invoke Expressions because the Entity Framework doesn’t support Expression.Invoke which is required to combine Expressions.

private class OrSpecification : Specification<T>
{
    private readonly ISpecification<T> left;
    private readonly ISpecification<T> right;
    public OrSpecification(ISpecification<T> left, ISpecification<T> right)
    {
        this.left = left;
        this.right = right;

        this._evalFunc =
            (Func<T, bool>)Func<T, bool>.Combine
            (left.EvalPredicate.Compile(),
            right.EvalPredicate.Compile());

        ParameterExpression parameter =
            Expression.Parameter(typeof(T), “p”);
        var invokedExpression =
            Expression.Invoke(left.EvalPredicate,
                right.EvalPredicate.Parameters.Cast<Expression>());
        _evalPredicate =
            Expression.Lambda<Func<T, bool>>
            (Expression.Or(right.EvalPredicate.Body,
            invokedExpression), right.EvalPredicate.Parameters);
    }
    public override bool Matches(T entity)
    {
        return EvalPredicate.Compile().Invoke(entity);
    }
}
The problem with the Specification as it is now, is that it fails when we combine Specifications into an OrSpecification or AndSpecification. You might notice that I added the _evalFunc member, this was an attempt to to use the overload of IQueryable<T>.Where that takes a Func<T> as the argument rather than the Expression<Func<T>> ; this approach work’s to a degree but you lose the ability to cast IQueryable<T> to ObjectQuery<T>. The other thing that I find enormously frustrating is that LINQ To Entity queries return’s a WhereSelectEnumerableIterator if I use the overloaded version of the Where extension method that takes the Func<T> as it’s argument and this means I am unable to cast it to ObjectQuery<T> which constricts our options in moving that strategy forward.
private static void CombinedOrSpecExample()
{
    Specification<Order> order_spec =
        new Specification<Order>(o => o.Order_Details.All
            (od => od.Product is DiscontinuedProduct));

    Specification<Order> german_customer_spec =
        new Specification<Order>(c => c.Customer.Country == “Germany”);

    var orSpec = order_spec | german_customer_spec;

    using (var ctx = new NorthwindEntities())
    {
        var orders =
            (ObjectQuery<Order>)
            from o in ctx.Orders
                .Include(“Order_Details”)
                .Include(“Customer”)
            .Where(orSpec.EvalFunc).AsQueryable<Order>()
             select o;

        Console.WriteLine(orders.ToTraceString());

        try
        {
            foreach (var order in orders)
            {
                var sumup =
                    order.Order_Details.Sum
                    (od => od.Quantity * od.UnitPrice);
                Console.WriteLine(“The sum of orders for order ID: {0} is {1}”,
                    order.OrderID.ToString(), sumup.ToString());
            }
        }
        catch (ArgumentException argEx)
        {
            Console.WriteLine(argEx.Message);
        }
    }
}

This code produces a casting error:

ef_specpattern_error_enumerable

which is as already stated, related to the issue created by using the .Where extension method that accepts a Func<T> as opposed to the Expression<Func<T, bool>>.
As I said it’s late and so far I have a big headache but I will persist.

Share/Save/Bookmark

7 comments

Creative Commons Attribution-ShareAlike 2.5 Australia
Creative Commons Attribution-ShareAlike 2.5 Australia