根据示例查询(Query By Example)

根据示例查询(QBE, Query By Example)是条件查询的一种特殊情况NHibernate.Criterion.Example 类根据你指定的实例创造查询条件。

其典型的用法:创建一个 Example实例;在 Example 实例上设置值;根据 Example 和设置 NHibernate 返回其对象集合。

 public IList<News> Query()
        {
            News news = new News() { Title = "XXX", Content = "哈哈哈" };
            return session.CreateCriteria(typeof(News))
            .Add(Example.Create(news)).List<News>();
        }
Code language: PHP (php)

调整 Example 使之更实用 ,比如忽略大小写等

public IList<News> UseQueryByExample_GetNewsnews()
        {
            Example example = Example.Create(news)
            .IgnoreCase()
            .EnableLike()
            .SetEscapeCharacter('&');
            return session.CreateCriteria(typeof(News))
            .Add(example)
            .List<News>();
        }
Code language: PHP (php)

利用 CriteriaAPI 按 Title和 Content查询新闻

 public IList<News> GetNewsByTitleAndContent(string title, string content)
        {
            return session.CreateCriteria(typeof(News))
            .Add(Restrictions.Eq("Title", title))
            .Add(Restrictions.Eq("Content", content))
            .List<News>();
        }
Code language: PHP (php)

利用 CriteriaAPI 获取新闻ID 大于 某个值的新闻

 public IList<News> GetNewsWithIdGreaterThan(int Id)
        {
            return session.CreateCriteria(typeof(News))
            .Add(Restrictions.Gt("ID", Id))
            .List<News>();
        }
Code language: PHP (php)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注