NHIBERNATE:与操作员查询
-
02-10-2019 - |
题
我正在寻找一种将或操作员构建到查询中的方法,以在表的一个字段以及连接表的另一个字段中查找特定值。这在SQL中是非常基本的,但是我不能为世界弄清楚如何在Nhibernate中做到这一点。我一直在搜索网络,但是我发现的示例对我来说很模糊,我发现它们很难应用于我的特定实现。
我有一个名为“派对”的类,带有一个名为参考的字符串,这是主要参考。新的要求要求该选项也能够为聚会添加大量侧参照。因此,我不得不添加另一个名为PartyReference的课程,该课程与政党有多一关系。
现在,有了给定的参考,我必须在此主要参考字段以及侧面参考中查看其价值。但是,只要我不知道该字段必须与该值相对应,或者是其他一个,我就无法使其起作用。
我做了一个看起来像这样的解决方法,但它是不高的和愚蠢的,因为必须有办法说“或”:
public Party GetPartyOnAnyReference(string reference)
{
Party party;
ISession session = Factory.OpenSession();
ITransaction tx = session.BeginTransaction();
try
{
//first search on main reference
ICriteria criteria1 = session.CreateCriteria(typeof(Party));
criteria1.Add(Restrictions.Eq("Reference", reference));
IList<Party> parties1 = criteria1.List<Party>();
party = parties1.Count > 0 ? parties1[0] : null;
//then try with side-references
if (party == null)
{
ICriteria criteria2 = session.CreateCriteria(typeof(Party));
criteria2
.SetFetchMode("References", FetchMode.Eager)
.CreateCriteria("References")
.Add(Expression.Eq("Reference", reference));
IList<Party> parties2 = criteria2.List<Party>();
party = parties2.Count > 0 ? parties2[0] : null;
}
session.Close();
}
catch (Exception e)
{
tx.Rollback();
session.Close();
if (e.GetType().ToString() == "NHibernate.ObjectNotFoundException")
party = null;
else throw;
}
return party;
}
我当然意识到,我也可以通过简单地将主要参考的主要参考来解决这个问题,并以其他参考作为派对报酬对待。但是在某个阶段,我无论如何都必须使用NHIBERNATE的或查询,因此我现在可以使用这种特殊情况来解决它。
有任何想法吗?
解决方案
您可以使用 Restrictions.Or
或对多个或使用析取。
session.CreateCriteria<Party>()
.CreateAlias("References", "r", JoinType.LeftOuterJoin)
.Add(Restrictions.Or(
Restrictions.Eq("Reference", reference),
Restrictions.Eq("r.Reference", reference)))
.SetResultTransformer(new DistinctRootEntityResultTransformer())
.List<Party>();
不隶属于 StackOverflow