Thursday, September 17, 2009

Xaf tip # 6 Linq your Session queries

Pretty silent these days eh? I am working on a big refactoring on DictionaryDifference and have not much time to blog.

But have another tip for my Xaf Tips series today maybe not strictly Xaf but is an XPO tip that you can use with your Xaf applications .

The Problem
Suppose your are a strongly typed fun like me or you want to use linq to query objects inside a transaction.

In order linq to be used with XPO DevExpress provides XPQuery<T> class but unfortunately this do not support transactions.

So the following test fails

var work = new UnitOfWork();
new User(work){UserName = "Sam"};

User firstOrDefault = new XPQuery<User>(work).Where(user => user.UserName == "Sam").FirstOrDefault();

Assert.IsNotNull(firstOrDefault);

The solution
XPQuery<ClassType> also provides a TransformExpression method that takes as an argument a lamda expression.

Aha some extension methods on that would be piece of cake

public static class SessionExtensions
{
    public static int GetCount<ClassType>(this Session session){
        return (int) session.Evaluate<ClassType>(new AggregateOperand("", Aggregate.Count), null);
    }
    public static object GetObject(this Session session, object o){
        if (o== null)
            return null;
        return session.GetObjectByKey(o.GetType(), ((PersistentBase)o).ClassInfo.KeyProperty.GetValue(o));
    }
    public static ClassType FindObject<ClassType>(this Session session,PersistentCriteriaEvaluationBehavior persistentCriteriaEvaluationBehavior, Expression<Func<ClassType,bool>> expression){
        return (ClassType)
            session.FindObject(persistentCriteriaEvaluationBehavior, typeof (ClassType), new XPQuery<ClassType>(session).TransformExpression(expression));
    }
    public static ClassType FindObject<ClassType>(this Session session, Expression<Func<ClassType,bool>> expression)
    {
        
        return (ClassType) session.FindObject(typeof(ClassType), new XPQuery<ClassType>(session).TransformExpression(expression), false);
    }
}

Now the test can be written using Linq To Xpo as

var work = new UnitOfWork();
new User(work){UserName = "Sam"};


User firstOrDefault = work.FindObject<User>(PersistentCriteriaEvaluationBehavior.InTransaction, user => user.UserName == "Sam");

Assert.IsNotNull(firstOrDefault);

and pass succesully !!

These goodies and much more are included at eXpand 

Happy Xaffing and see you at the next tip

Technorati Tags: ,,

Subscribe to XAF feed
Subscribe to community feed

DiggIt!
blog comments powered by Disqus