Sony Arouje

a programmer's log

Lambda expression validation against Entity

leave a comment »

The system that I was building, I created a generic Record exist validator. What this does is check whether a specific record exist in the database. Say user can pass a Product code and check whether the Product exist in the database. In some scenario just checking a Product exist may not be sufficient, say while doing an invoice we should validate and raise error if a product is soft deleted but in some scenario we need to check whether the product exist nothing more. That means this custom status check should not implemented to the core Product exist validator. Developer should inject the custom Error condition logic based on the functionality he is working. This post explains the Custom Error conditions logic I implemented based on Lambda expression.

Lambda expression Validation

The easy way for a developer to write a Error condition using Lambda expression, pseudo code will be some thing like this.

(product=>product.isDeleted==true) then raise exception.

Initial 30 minutes I was thinking how to get the body of expression and validate the entity because we cannot directly apply Lambda expression to an entity like Product. When I go deeper into expression evaluation, I realize that I need more time than anticipated and might ended up with a complex functionality. This is what I did to solve this scenario.

  1. Add the entity to validate to a generic List
  2. Pass the lambda expression to Where() of the list.
  3. If the result count is greater than 0 raise the error.

see the code below.

public class ErrorCondition
    private object _criteria;
    private Exception _exceptionToRaise = null;

    public ErrorCondition IfTrue<T>(Func<T, bool> criteria) where T:class
        _criteria = criteria;
        return this;

    public void RaiseException(Exception exceptionToRaise)
        this._exceptionToRaise = exceptionToRaise;
        return this;

    internal void Validate<T>(T entity)
        List<T> tmp = new List<T>();
        Func<T, bool> criteria = (Func<T, bool>)this._criteria;
        var result = tmp.Where<T>(criteria).ToList<T>();
        if (result.Count > 0)
            if (_exceptionToRaise == null)
                throw new Exceptions.MaginusException("Error Condition is matching but 
                  no exception attached to ErrorCondition. Please set exception via 
                  RaiseException function.");
            throw _exceptionToRaise;


User can create a custom error condition as shown below.

ErrorCondition isDeletedCheckCondition = new ErrorCondition();
isDeletedCheckCondition.IfTrue<Product>(p => p.IsDeleted== true)
    .RaiseException(new Exception("Product is deleted"));

I created a class to group multiple error conditions user may need to add.

public class ErrorConditions
    IList<ErrorCondition> _errorConditions;
    public ErrorConditions()
        _errorConditions = new List<ErrorCondition>();

    public ErrorConditions Add(ErrorCondition condition)
        return this;

    internal void Validate<T>(T entity)
        foreach (ErrorCondition errCondition in _errorConditions)

Now user can add multiple Error conditions as shown below.

ErrorConditions errorConditions = new ErrorConditions()
    .Add(new ErrorCondition().IfTrue<Product>(p => p.IsDeleted == true)
       .RaiseException(new Exception("Product is deleted and cannot be added")))
    .Add(new ErrorCondition().IfTrue<Product>(p => p.IsWithdrawn == true)
       .RaiseException(new Exception("Product is withdrawn.")));

Pass this errorConditions instance to Product Exist validator, Validator will call errorConditions.Validate<Product>(productToValidate) if the record exist in the database.

The key point to note here is, how we could evaluate an expression with the help of a List. Other wise I have to come up with complex code to analyze the body of the expression and things like that.

Happy coding…


Written by Sony Arouje

February 4, 2014 at 3:19 pm

Posted in .NET

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: