使用NHibernate查询DataBase的规范模式

时间:2009-05-09 21:21:30

标签: nhibernate specification-pattern

如何使用NHibernate实现查询数据库的规范模式?(没有LINQ到NHibernate)。我阅读了很多关于规范模式的内容,但大部分是关于验证和查询内存集合对象的。

据我所知,在规范界面中使用DetachedCriteria的最佳方法就像这样。

interface ISpecification<T> {

 bool IsSatisfiedBy(T object);

 DetachedCriteria CreateCriteria();

}

有没有替代或更好的方法来做到这一点?

2 个答案:

答案 0 :(得分:3)

这不是更好,但可以替代

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

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

易于使用linq(对nhibernate)和内存集合。

答案 1 :(得分:0)

我使用简单的扩展方法和规范模式实现了这个,适用于System.Linq.IQueryable列表。

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));
    }
}

简单的示例类和IFilter实现:

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));
    }
}

用法:

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