3

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

据我所知,在这样的规范接口中使用 DetachedCriteria 的最佳方法。

interface ISpecification<T> {

 bool IsSatisfiedBy(T object);

 DetachedCriteria CreateCriteria();

}

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

4

2 回答 2

3

这不是更好,但可以替代

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

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

易于在 linq(休眠)和内存集合上使用。

于 2009-05-10T09:20:48.540 回答
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);
于 2014-06-19T09:39:03.737 回答