tags:

views:

23

answers:

1

The Example class is great if you are specifying which properties you want to exclude from the example. But what if you want to specify which properties to include?

Take this example: looking for people in the database that have the same name. A Person object has many properties. So to use the NHibernate.Criterion.Example object I would have to specify every field to exclude - which could be many.

Why is there no IncludeProperty method?

I have a Person object and I want to see if it is a duplicte based on pre-set business rules (FirstName, LastName, DateOfBirth). These rules could be changed to include a postcode or something else - and I'd like to make that configurable.

Is there an easy way around this?

+1  A: 

I have a solution to the IncludeProperty issue:

private Type persitentType = typeof(T);
public IList<T> GetByExample(T exampleInstance, params string[] propertiesToInclude)
{
    // get the properties that will be excluded
    List<string> propertiesToExclude =
        persitentType.GetProperties().Where(p => propertiesToInclude.Contains(p.Name) == false).Select(p => p.Name).ToList();

    // create the criteria based on the example and excluding the given properties
    ICriteria criteria = NHibernateSession.CreateCriteria(persitentType);
    Example example = Example.Create(exampleInstance);
    foreach (string propertyToExclude in propertiesToExclude)
    {
        example.ExcludeProperty(propertyToExclude);
    }
    criteria.Add(example);

    // return the result 
    return criteria.List<T>();
}

Add this method to your repository class. It uses reflection to determine what properties the specified object has, and then finds the properties to exclude based on those that have been specified as includes.

CarllDev