1

我正在尝试为 NHibernate 创建 SQL 查询:

SQL 看起来像这样:

Select p.*
From PPoint p
Inner join PPFile f on p.ImportID = f.ImportID
where p.Name like '%a%'
Or p.Code like '%a%'
Or f.FileName like '%a%'

找不到一个像样的例子,即使听起来很容易做到。

目前我有:

        var pointList = session
            .CreateCriteria(typeof(PPoint))
           .Add(Restrictions.Or(Restrictions.Or(Restrictions.Or(Restrictions.Or
                Restrictions.Like("Name", "%" + search + "%"),
                Restrictions.Like("Code", "%" + search + "%")),
                Restrictions.Like("Test", "%" + search + "%")),
                Restrictions.Like("Test2", "%" + search + "%")),
                Restrictions.Like("FileName", "%" + search + "%")))
            .List<PPoint>();

NHibernate 2.2 版

4

2 回答 2

1

找到解决方案:

var pointList = session
                .CreateCriteria(typeof(PPoint), "p")
                .CreateAlias("ImportFile", "f", NHibernate.SqlCommand.JoinType.InnerJoin)
                .Add(Restrictions.Disjunction()
                    .Add(Restrictions.Like("p.Name", search, MatchMode.Anywhere))
                    .Add(Restrictions.Like("p.Code", search, MatchMode.Anywhere))
                    .Add(Restrictions.Like("p.Test1", search, MatchMode.Anywhere))
                    .Add(Restrictions.Like("p.Test2", search, MatchMode.Anywhere))
                    .Add(Restrictions.Like("f.FileName", search, MatchMode.Anywhere)))
                .List<PPoint>();

主要是在映射文件中描述关系:

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
                   assembly="AAA.Data"
                   namespace="AAA.Data.Domain">

  <class name="PPoint" lazy="true">
    <id name="PPointID" />
    <!--<property name="ImportID" />-->
    <many-to-one name="ImportFile" column="ImportID" not-null="true" cascade="all-delete-orphan" />

    <property name="Code" />
    <property name="Test1" />

    ...
  </class>

于 2013-02-04T22:26:27.477 回答
0

您使用的是 nHibernate 3.0 或更高版本吗?这种查询非常适合QueryOver API

string searchString = string.Format("%{0}%", search);
PPoint ppointAlias = null;
PPFile ppFileAlias = null;
var pointList = session.QueryOver<PPoint>(() => ppointAlias)
                       .JoinQueryOver<PPFile>(ppPoint => ppPoint.ImportFile, () => ppFileAlias)
                       .Where(
                                 Restrictions.On(() => ppointAlias.Name).IsLike(searchString))
                                              ||
                                 Restrictions.On(() => ppointAlias.Code).IsLike(searchString))
                                              ||
                                 Restrictions.On(() => ppFileAlias.FileName).IsLike(searchString))
                              )
                        .List();
于 2013-02-04T22:26:45.280 回答