NHibernate-根据子属性过滤出结果
本文关键字:过滤 结果 属性 NHibernate- | 更新日期: 2023-09-27 17:53:13
我有这段代码获取所有启用的组及其子组。我遇到的问题是,孩子们也可能是残疾人,但我无法让流利的nhibernate只获取所有孩子都启用的组。我想这是可能的,但怎么可能呢?
public class Group {
public bool IsDisabled { get; set; }
public string Description { get; set; }
public ICollection<ChildType> Children { get; protected set; }
}
public class ChildType {
public bool IsDisabled { get; set; }
public string Description { get; set; }
}
public IList<Group> Search(string searchString) {
IQueryOver<Group> query = Session.QueryOver<Group>()
.WhereRestrictionOn(x => x.Description).IsInsensitiveLike(searchString, MatchMode.Start)
.Where(x => !x.IsDisabled)
.OrderBy(x => x.Description).Asc
.Fetch(group => group.Children).Eager;
return query
.Cacheable()
.List();
}
编辑:儿童和组之间存在N:M关系。
以下是我使用的解决方案:
public class Group {
public long Id { get; set; }
public bool IsDisabled { get; set; }
public string Description { get; set; }
public ICollection<ChildType> Children { get; protected set; }
}
public class ChildType {
public long Id { get; set; }
public bool IsDisabled { get; set; }
public string Description { get; set; }
public ICollection<Group> Groups { get; protected set; }
}
public IList<Group> Search(string searchString) {
ChildType child = null;
Group group = null;
Group joinedGroup = null;
var notDisabled = Session.QueryOver.Of<ExaminationType>()
.Where(x => x.IsDisabled)
.JoinAlias(x => x.Groups, () => joinedGroup )
.Where(x => joinedGroup == group)
.Select(x => x.Id);
IQueryOver<Group> query = Session.QueryOver<Group>()
.WhereRestrictionOn(x => x.Description).IsInsensitiveLike(searchString, MatchMode.Start)
.JoinAlias(x => x.ExaminationTypes, () => child)
.WithSubquery.WhereNotExists(notDisabled)
.OrderBy(x => x.Description).Asc;
return query
.Cacheable()
.List();
}
您需要使用子查询来实现您想要的。不过,为了做到这一点,您需要添加一个对ChildType实体的Group引用。
Group group = null;
var childCrit = QueryOver.Of<ChildType>()
.Where(c => c.Group == group).And(c => c.IsDisabled)
.Select(c => c.Id);
var query = Session.QueryOver(() => group)
.WhereRestrictionOn(x => x.Description).IsInsensitiveLike(searchString, MatchMode.Start)
.Where(x => !x.IsDisabled)
.WithSubquery.WhereNotExists(childCrit)
.OrderBy(x => x.Description).Asc
.Fetch(group => group.Children).Eager;
这将得到所有没有残疾和没有残疾儿童的组。
public IList<Group> Search(string searchString) {
Children children = null;
IQueryOver<Group> query = Session.QueryOver<Group>()
.WhereRestrictionOn(x => x.Description).IsInsensitiveLike(searchString, MatchMode.Start)
.Where(x => !x.IsDisabled)
.JoinAlias(x => x.Children, () => children)
.Where(x => !x.IsDisabled)
.OrderBy(x => x.Description).Asc;
return query
.Cacheable()
.List();
}
这应该做你想做的事。
加入别名也会为您获取别名。
http://www.philliphaydon.com/2011/04/nhibernate-querying-relationships-are-depth/