XML 字段上的 Nhibernate 和类似语句

Nhibernate and like statement on XML field

我有一个包装好的 fluent nhibernate 框架,我正在重复使用它并且无法控制实际映射。

在我的实体对象中,我将 属性 作为字符串映射到 sql 中的 XML 列。

因此,当我 运行 查询时:

var myResult = (from myTable in DataManager.Session.Query<Table>()
                      where myTable.thatXmlFieldWhichIsMappedAsString.Contains(AnXmlSnippet))
                      select myTable).FirstOrDefault();

它试图在 SQL 中使用 LIKE 运算符,这对该列类型无效。

如何解决这个问题而不必先 select 所有行并先转换为列表?

如果我们不需要 .Query() (LINQ),我们可以使用 Criteria 查询或 QueryOver,我们可以使用转换:

// the projection of the column with xml
// casted to nvarchar
var projection = Projections
      .Cast(NHibernateUtil.StringClob
          , Projections.Property("thatXmlFieldWhichIsMappedAsString"));

// criteria filtering with LIKE
var criteria = Restrictions.Like(projection, "searched xml");

// query and result
var query = session.QueryOver<MyEntity>()
    .Where(criteria)
    ;
var result = query 
    .SingleOrDefault<MyEntity>()
    ;

根据我的经验,这可能导致转换为小型 nvarchar(255) - sql 服务器...然后我们可以这样做:

var projection = Projections
   .SqlProjection("CAST(thatXmlFieldWhichIsMappedAsString as nvarchar(max)) AS str"
       , new string[]{}
       , new NHibernate.Type.IType[]{}
   );