NHibernate:条件/子条件投影 [英] NHibernate: Criteria/SubCriteria Projection
问题描述
我有一个Mod类,它有一个成员:
I have a class Mod, which has a member:
ICollection<Event> EventList
Event类有一个成员:
The class Event has a member:
public virtual EventType Type { get; set; }
EvenType类具有成员:
The class EvenType has member:
public virtual int Id
我想使用NHibernate标准获取ID为1或2的Mod中所有事件的列表.我是这样做的:
I want to get a list of all Events in Mod which have an id of 1 or 2 using NHibernate Criteria. I did this:
var subCriteria = DetachedCriteria.For<Mod>()
.Add(Restrictions.In("Event.Type", new int[] {1, 2 })
);
criteria.Add(Subqueries.Exists(subCriteria));
但是出现运行时错误提示 没有投影就无法在条件上使用子查询.
but I get a runtime error saying Cannot use subqueries on a criteria without a projection.
那么,很好,但是我不知道该投影仪要放什么.我可以找到有关如何进行投影的示例,但没有什么可以真正解释其目的.我已经尝试了各种方法,但是都导致了运行时错误:
So, fine, but I don't know what to put for the Projection. I can find examples of how to do Projections, but nothing that really explains the purpose. I've tried various things, but all result in a runtime error:
消息:值不能为null. 参数名称:键 资料来源:mscorlib 帮助链接: ParamName:键
Message : Value cannot be null. Parameter name: key Source : mscorlib Help link : ParamName : key
我需要使用子查询,因为当此方法可行时,我将添加更多子查询.
I need to use subquery because I will be adding more when this works.
您能建议做什么投影吗?
Can you suggest what to do for Projection?
推荐答案
As documented here: 16.4. Associations it could be done like this:
IQueryOver<Mod, Event> query = session
.QueryOver<Mod>()
.JoinQueryOver<Event>(mod => mod.EventList)
.WhereRestrictionOn(evnt => evnt.Type.Id).IsIn(new object[] { 1, 2});
var result = query.List<Mod>();
纯标准API:
var criteria = session.CreateCriteria<Mod>();
var sub = criteria.CreateCriteria("EventList", JoinType.LeftOuterJoin);
sub.Add(new InExpression("Type", new object[] { 1, 2 }));
var result = criteria.List<Mod>();
使用分离的条件.在这种情况下,EventType
必须具有属性ModId
或引用Mod
实例.在子查询中,我们必须返回有效的Mod.ID列表
using detached criteria. In this case, the EventType
must have property ModId
or refernece to the Mod
instance. In the subquery, we have to return list of valid Mod.IDs
var sub = DetachedCriteria
.For<Event>()
.Add(Restrictions.In("Type", new int[] {1, 2 })) // WHERE
.SetProjection(Projections.Property("ModId")); // Mod.ID the SELECT clause
var criteria = session.CreateCriteria<Mod>();
criteria.Add(Subqueries.PropertyIn("ID", sub)); // Mod.ID in (select
var result = criteria.List<Mod>();
这篇关于NHibernate:条件/子条件投影的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!