Specification template for querying a database using NHibernate

How to execute a specification template for querying a database using NHibernate? (without LINQ to NHibernate). I read a lot about the specification template, but most of them dealt with objects for collecting and checking memory objects.

The best way, as far as I know, is using DetachedCriteria in a specification interface like this.

interface ISpecification<T> {

 bool IsSatisfiedBy(T object);

 DetachedCriteria CreateCriteria();

}

Is there an alternative or better way to do this?

+3
source share
3 answers

It is not better, but may be an alternative.

interface ISpecification<T> 
{
   bool IsSatisfiedBy(T object);

   Expression<Func<T, bool>> Predicate { get; }
}

Easy to use over linq (for nhibernate) and memory collections.

+3
source

I implemented this using a simple extension method and specification template, works for System.Linq.IQueryable lists.

public interface IFilter<in T>
{
    bool MatchFilter(T o);
}

public static class FilterExtension
{
    public static IQueryable<T> Filter<T>(this IQueryable<T> query, IFilter<T> filter)
    {
        return query.Where(x => filter.MatchFilter(x));
    }
}

Simple sample classes and IFilter implementation:

public class Organization
{
    public string Name { get; set; }
    public string Code { get; set; }
    public Address Address { get; set; }


    public Organization(string name, string code, string city, string country)
    {
        Name = name;
        Code = code;
        Address = new Address(city, country);
    }

}

public class Address
{
    public Address(string city, string country)
    {
        City = city;
        Country = country;
    }

    public string City { get; set; }
    public string Country { get; set; }
}

public class GenericOrganizationFilter : IFilter<Organization>
{
    public string FilterString { get; set; }

    public GenericOrganizationFilter(string filterString)
    {
        FilterString = filterString;
    }

    public bool MatchFilter(Organization o)
    {
        return
            (o.Name != null && o.Name.Contains(FilterString)) ||
            (o.Code != null && o.Code.Contains(FilterString)) ||
            (o.Address != null && o.Address.City != null && o.Address.City.Contains(FilterString)) || 
            (o.Address != null && o.Address.Country != null && o.Address.Country.Contains(FilterString));
    }
}

Using:

IFilter<Organization> filter = new GenericOrganizationFilter("search string");
//Assuming queryable is an instance of IQueryable<Organization>. 
IQueryable<Organization> filtered = queryable.Filter(filter);
0
source

Source: https://habr.com/ru/post/1708010/


All Articles