2017-08-03 191 views
1

为了简化NHibernate的限制一样,我们想有两个实体:嵌套字符串属性

public class Entity 
{ 
    public string Value { get; set; } 

    public ChildEntity Child { get; set; } 
} 

public class ChildEntity 
{ 
    public string Value { get; set; } 
} 

我需要找到任何ValueChild.Value不敏感等指定字符串query所有实体。

这就是我现在:

Entity entity = null; 
ChildEntity child = null; 

var nhibernateQuery = session 
    .QueryOver(() => entity) 
    .JoinAlias(() => entity.Child,() => child); 

if (!string.IsNullOrWhiteSpace(query)) 
{ 
    nhibernateQuery = nhibernateQuery 
     .Where(
      Restrictions.Or(
       Restrictions.On(() => entity).IsInsensitiveLike(query), 
       Restrictions.On(() => child).IsInsensitiveLike(query) 
      ) 
     ); 
} 

return nhibernateQuery.List().ToArray(); 

我得到NullReferenceException - 好像Restrictions.On不能正确处理别名。

,我曾尝试另一种方法是.JoinQueryOver()这是由this post建议:

return session 
    .QueryOver<Entity>() 
     .Where(Restrictions.InsensitiveLike("Value", query)) 
    .JoinQueryOver(e => e.Child) 
     .Where(Restrictions.InsensitiveLike("Value", query)); 

这个事情的作品,除了一两件事:它返回其中两个ValueChild.Value就像query所有项目。我需要相同的东西,但逻辑为or

应该怎么做才能使它工作?我想使用.QueryOver(),无论是否带有别名,但没有.CreateCriteria(),但是如果您能帮助我解决任何工作问题,我们将不胜感激。

+0

您是否添加了MatchMode选项? –

+0

@WillyDavidJr你能解释一下你的意思吗? MatchMode只影响字符串的比较方式,不是吗?没有更多的相关代码比这个最小的例子。 –

回答

0

该问题已通过使用NHibernate LINQ .Query<>()解决。
它可以自己解决所有连接和关系。
与此同时,.Contains()方法被翻译成适合我需要的MS SQL的大小写不敏感的LIKE语句。

var nhibernateQuery = session 
    .Query<Entity>(); 

if (!string.IsNullOrWhiteSpace(query)) 
{ 
    nhibernateQuery = nhibernateQuery 
     .Where(e => e.Value.Contains(query) || e.Child.Value.Contains(query)); 
} 

return nhibernateQuery.ToArray();