Using the rules engine

PLINQO gives you several ways to lay down the law. You add rules in code or declare them with attributes. You can enforce constraints such as property length and required fields, validate data with regular expressions, and use several built-in rules, including authorization rules.

Before any data is saved, PLINQO runs the rules against every entity in your change set. If any rule is broken, it throws a BrokenRulesException with a list of the broken rules, and nothing is saved.

Add a custom rule

The PLINQO rule manager generates rules from the database schema, and you can add your own rules to the collection. Add custom rules in the AddSharedRules partial method of each entity. For example, this rule sets a minimum length for UserName:

static partial void AddSharedRules()
{
    RuleManager.AddShared(new CustomRule("UserName", "UserName must be 5 characters.", MinLengthUserName));
}

private static bool MinLengthUserName(string username)
{
    if (String.IsNullOrEmpty(username) || username.Length < 5)
        return false;
    else
        return true;
}

When a rule is broken, no data is updated, and you get a list of the broken rules. For example, this code saves a user with no user name, so SubmitChanges throws a BrokenRulesException:

using (var context = new TrackerDataContext())
{
    User user = new User();
    context.User.InsertOnSubmit(user);
    context.SubmitChanges();
}

Declare rules with attributes

You can also declare rules with attributes in the entity's metadata class. PLINQO supports the standard rules in the System.ComponentModel.DataAnnotations assembly, as well as the rules PLINQO defines.

For an example that uses every built-in rule, both in code and as attributes, see Rules example code.