-
Notifications
You must be signed in to change notification settings - Fork 933
/
Copy pathquery_queryover.xml
434 lines (393 loc) · 18.8 KB
/
query_queryover.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<chapter id="queryqueryover">
<title>QueryOver Queries</title>
<para>
The ICriteria API
is NHibernate's implementation of Query Object.
NHibernate 3.0 introduces the QueryOver API, which combines the use of
Extension Methods
and
Lambda Expressions
(both new in .Net 3.5) to provide a statically type-safe wrapper round the ICriteria API.
</para>
<para>
QueryOver uses Lambda Expressions to provide some extra
syntax to remove the 'magic strings' from your ICriteria queries.
</para>
<para>
So, for example:
</para>
<programlisting><![CDATA[.Add(Expression.Eq("Name", "Smith"))]]></programlisting>
<para>becomes:</para>
<programlisting><![CDATA[.Where<Person>(p => p.Name == "Smith")]]></programlisting>
<para>
With this kind of syntax there are no 'magic strings', and refactoring tools like
'Find All References', and 'Refactor->Rename' work perfectly.
</para>
<para>
Note: QueryOver is intended to remove the references to 'magic strings'
from the ICriteria API while maintaining it's opaqueness. It is <emphasis role="underline">not</emphasis> a LINQ provider;
NHibernate has a built-in <link linkend="querylinq">Linq provider</link> for this.
</para>
<sect1 id="queryqueryover-querystructure">
<title>Structure of a Query</title>
<para>
Queries are created from an ISession using the syntax:
</para>
<programlisting><![CDATA[IList<Cat> cats =
session.QueryOver<Cat>()
.Where(c => c.Name == "Max")
.List();]]></programlisting>
<para> </para>
<para>
Detached QueryOver (analogous to DetachedCriteria) can be created, and then used with an ISession using:
</para>
<programlisting><![CDATA[QueryOver<Cat> query =
QueryOver.Of<Cat>()
.Where(c => c.Name == "Paddy");
IList<Cat> cats =
query.GetExecutableQueryOver(session)
.List();]]></programlisting>
<para>
Queries can be built up to use restrictions, projections, and ordering using
a fluent inline syntax:
</para>
<programlisting><![CDATA[var catNames =
session.QueryOver<Cat>()
.WhereRestrictionOn(c => c.Age).IsBetween(2).And(8)
.Select(c => c.Name)
.OrderBy(c => c.Name).Asc
.List<string>();]]></programlisting>
</sect1>
<sect1 id="queryqueryover-simpleexpressions">
<title>Simple Expressions</title>
<para>
The Restrictions class (used by ICriteria) has been extended to include overloads
that allow Lambda Expression syntax. The Where() method works for simple expressions (<, <=, ==, !=, >, >=)
so instead of:
</para>
<programlisting><![CDATA[ICriterion equalCriterion = Restrictions.Eq("Name", "Max")]]></programlisting>
<para>
You can write:
</para>
<programlisting><![CDATA[ICriterion equalCriterion = Restrictions.Where<Cat>(c => c.Name == "Max")]]></programlisting>
<para> </para>
<para>
Since the QueryOver class (and IQueryOver interface) is generic and knows the type of the query,
there is an inline syntax for restrictions that does not require the additional qualification
of class name. So you can also write:
</para>
<programlisting><![CDATA[var cats =
session.QueryOver<Cat>()
.Where(c => c.Name == "Max")
.And(c => c.Age > 4)
.List();]]></programlisting>
<para>
Note, the methods Where() and And() are semantically identical; the And() method is purely to allow
QueryOver to look similar to HQL/SQL.
</para>
<para> </para>
<para>
Boolean comparisons can be made directly instead of comparing to true/false:
</para>
<programlisting><![CDATA[ .Where(p => p.IsParent)
.And(p => !p.IsRetired)]]></programlisting>
<para> </para>
<para>
Simple expressions can also be combined using the || and && operators. So ICriteria like:
</para>
<programlisting><![CDATA[ .Add(Restrictions.And(
Restrictions.Eq("Name", "test name"),
Restrictions.Or(
Restrictions.Gt("Age", 21),
Restrictions.Eq("HasCar", true))))]]></programlisting>
<para>
Can be written in QueryOver as:
</para>
<programlisting><![CDATA[ .Where(p => p.Name == "test name" && (p.Age > 21 || p.HasCar))]]></programlisting>
<para> </para>
<para>
Each of the corresponding overloads in the QueryOver API allows the use of regular ICriterion
to allow access to private properties.
</para>
<programlisting><![CDATA[ .Where(Restrictions.Eq("Name", "Max"))]]></programlisting>
<para> </para>
<para>
It is worth noting that the QueryOver API is built on top of the ICriteria API. Internally the structures are the same, so at runtime
the statement below, and the statement above, are stored as exactly the same ICriterion. The actual Lambda Expression is not stored
in the query.
</para>
<programlisting><![CDATA[ .Where(c => c.Name == "Max")]]></programlisting>
</sect1>
<sect1 id="queryqueryover-additionalrestrictions">
<title>Additional Restrictions</title>
<para>
Some SQL operators/functions do not have a direct equivalent in C#.
(e.g., the SQL <literal>where name like '%anna%'</literal>).
These operators have overloads for QueryOver in the Restrictions class, so you can write:
</para>
<programlisting><![CDATA[ .Where(Restrictions.On<Cat>(c => c.Name).IsLike("%anna%"))]]></programlisting>
<para>
There is also an inline syntax to avoid the qualification of the type:
</para>
<programlisting><![CDATA[ .WhereRestrictionOn(c => c.Name).IsLike("%anna%")]]></programlisting>
<para> </para>
<para>
While simple expressions (see above) can be combined using the || and && operators, this is not possible with the other
restrictions. So this ICriteria:
</para>
<programlisting><![CDATA[ .Add(Restrictions.Or(
Restrictions.Gt("Age", 5)
Restrictions.In("Name", new string[] { "Max", "Paddy" })))]]></programlisting>
<para>
Would have to be written as:
</para>
<programlisting><![CDATA[ .Add(Restrictions.Or(
Restrictions.Where<Cat>(c => c.Age > 5)
Restrictions.On<Cat>(c => c.Name).IsIn(new string[] { "Max", "Paddy" })))]]></programlisting>
<para>
However, in addition to the additional restrictions factory methods, there are extension methods to allow
a more concise inline syntax for some of the operators. So this:
</para>
<programlisting><![CDATA[ .WhereRestrictionOn(c => c.Name).IsLike("%anna%")]]></programlisting>
<para>
May also be written as:
</para>
<programlisting><![CDATA[ .Where(c => c..Name.IsLike("%anna%"))]]></programlisting>
</sect1>
<sect1 id="queryqueryover-associations">
<title>Associations</title>
<para>
QueryOver can navigate association paths using JoinQueryOver() (analogous to ICriteria.CreateCriteria() to create sub-criteria).
</para>
<para>
The factory method QuerOver<T>() on ISession returns an IQueryOver<T>.
More accurately, it returns an IQueryOver<T,T> (which inherits from IQueryOver<T>).
</para>
<para>
An IQueryOver has two types of interest; the root type (the type of entity that the query returns),
and the type of the 'current' entity being queried. For example, the following query uses
a join to create a sub-QueryOver (analogous to creating sub-criteria in the ICriteria API):
</para>
<programlisting><![CDATA[IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.JoinQueryOver(c => c.Kittens)
.Where(k => k.Name == "Tiddles");]]></programlisting>
<para>
The JoinQueryOver returns a new instance of the IQueryOver than has its root at the Kittens collection.
The default type for restrictions is now Kitten (restricting on the name 'Tiddles' in the above example),
while calling .List() will return an IList<Cat>. The type IQueryOver<Cat,Kitten> inherits from IQueryOver<Cat>.
</para>
<para>
Note, the overload for JoinQueryOver takes an IEnumerable<T>, and the C# compiler infers the type from that.
If your collection type is not IEnumerable<T>, then you need to qualify the type of the sub-criteria:
</para>
<programlisting>IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.JoinQueryOver<<emphasis>Kitten</emphasis>>(c => c.Kittens)
.Where(k => k.Name == "Tiddles");</programlisting>
<para> </para>
<para>
The default join is an inner-join. Each of the additional join types can be specified using
the methods <code>.Inner, .Left, .Right,</code> or <code>.Full</code>.
For example, to left outer-join on Kittens use:
</para>
<programlisting><![CDATA[IQueryOver<Cat,Kitten> catQuery =
session.QueryOver<Cat>()
.Left.JoinQueryOver(c => c.Kittens)
.Where(k => k.Name == "Tiddles");]]></programlisting>
</sect1>
<sect1 id="queryqueryover_entityjoin">
<title>Join entities without association (Entity joins or ad hoc joins)</title>
<para>
In QueryOver you have the ability to define a join to any entity, not just through a mapped association.
To achieve it, use <literal>JoinEntityAlias</literal> and <literal>JoinEntityQueryOver</literal>. By example:
</para>
<programlisting><![CDATA[Cat cat = null;
Cat joinedCat = null;
var uniquelyNamedCats = sess.QueryOver<Cat>(() => cat)
.JoinEntityAlias(
() => joinedCat,
() => cat.Name == joinedCat.Name && cat.Id != joinedCat.Id,
JoinType.LeftOuterJoin)
.Where(() => joinedCat.Id == null)
.List();]]></programlisting>
</sect1>
<sect1 id="queryqueryover-aliases">
<title>Aliases</title>
<para>
In the traditional ICriteria interface aliases are assigned using 'magic strings', however their value
does not correspond to a name in the object domain. For example, when an alias is assigned using
<code>.CreateAlias("Kitten", "kittenAlias")</code>, the string "kittenAlias" does not correspond
to a property or class in the domain.
</para>
<para>
In QueryOver, aliases are assigned using an empty variable.
The variable can be declared anywhere (but should
be <code>null</code> at runtime). The compiler can then check the syntax against the variable is
used correctly, but at runtime the variable is not evaluated (it's just used as a placeholder for
the alias).
</para>
<para>
Each Lambda Expression function in QueryOver has a corresponding overload to allow use of aliases,
and a .JoinAlias function to traverse associations using aliases without creating a sub-QueryOver.
</para>
<programlisting><![CDATA[Cat catAlias = null;
Kitten kittenAlias = null;
IQueryOver<Cat,Cat> catQuery =
session.QueryOver<Cat>(() => catAlias)
.JoinAlias(() => catAlias.Kittens, () => kittenAlias)
.Where(() => catAlias.Age > 5)
.And(() => kittenAlias.Name == "Tiddles");]]></programlisting>
</sect1>
<sect1 id="queryqueryover-projections">
<title>Projections</title>
<para>
Simple projections of the properties of the root type can be added using the <code>.Select</code> method
which can take multiple Lambda Expression arguments:
</para>
<programlisting><![CDATA[var selection =
session.QueryOver<Cat>()
.Select(
c => c.Name,
c => c.Age)
.List<object[]>();]]></programlisting>
<para>
Because this query no longer returns a Cat, the return type must be explicitly specified.
If a single property is projected, the return type can be specified using:
</para>
<programlisting><![CDATA[IList<int> ages =
session.QueryOver<Cat>()
.Select(c => c.Age)
.List<int>();]]></programlisting>
<para>
However, if multiple properties are projected, then the returned list will contain
object arrays, as per a projection
in ICriteria. This could be fed into an anonymous type using:
</para>
<programlisting><![CDATA[var catDetails =
session.QueryOver<Cat>()
.Select(
c => c.Name,
c => c.Age)
.List<object[]>()
.Select(properties => new {
CatName = (string)properties[0],
CatAge = (int)properties[1],
});
Console.WriteLine(catDetails[0].CatName);
Console.WriteLine(catDetails[0].CatAge);]]></programlisting>
<para>
Note that the second <code>.Select</code> call in this example is an extension method on IEnumerable<T> supplied in System.Linq;
it is not part of NHibernate.
</para>
<para> </para>
<para>
QueryOver allows arbitrary IProjection to be added (allowing private properties to be projected). The Projections factory
class also has overloads to allow Lambda Expressions to be used:
</para>
<programlisting><![CDATA[var selection =
session.QueryOver<Cat>()
.Select(Projections.ProjectionList()
.Add(Projections.Property<Cat>(c => c.Name))
.Add(Projections.Avg<Cat>(c => c.Age)))
.List<object[]>();]]></programlisting>
<para> </para>
<para>
In addition there is an inline syntax for creating projection lists that does not require the explicit class qualification:
</para>
<programlisting><![CDATA[var selection =
session.QueryOver<Cat>()
.SelectList(list => list
.Select(c => c.Name)
.SelectAvg(c => c.Age))
.List<object[]>();]]></programlisting>
<para> </para>
<para>
Projections can also have arbitrary aliases assigned to them to allow result transformation.
If there is a CatSummary DTO class defined as:
</para>
<programlisting><![CDATA[public class CatSummary
{
public string Name { get; set; }
public int AverageAge { get; set; }
}]]></programlisting>
<para>
... then aliased projections can be used with the AliasToBean<T> transformer:
</para>
<programlisting><![CDATA[CatSummary summaryDto = null;
IList<CatSummary> catReport =
session.QueryOver<Cat>()
.SelectList(list => list
.SelectGroup(c => c.Name).WithAlias(() => summaryDto.Name)
.SelectAvg(c => c.Age).WithAlias(() => summaryDto.AverageAge))
.TransformUsing(Transformers.AliasToBean<CatSummary>())
.List<CatSummary>();]]></programlisting>
</sect1>
<sect1 id="queryqueryover-projectionfunctions">
<title>Projection Functions</title>
<para>
In addition to projecting properties, there are extension methods to allow certain common dialect-registered
functions to be applied. For example you can write the following to get 3 letters named people.
</para>
<programlisting><![CDATA[ .Where(p => p.FirstName.StrLength() == 3)]]></programlisting>
<para>
The functions can also be used inside projections:
</para>
<programlisting><![CDATA[ .Select(
p => Projections.Concat(p.LastName, ", ", p.FirstName),
p => p.Height.Abs())]]></programlisting>
</sect1>
<sect1 id="queryqueryover-projectionentities">
<title>Entities Projection</title>
<para>
You can add entity projections via the <literal>AsEntity()</literal> extension.
</para>
<programlisting><![CDATA[Cat mate = null;
var catAndMateNameList = sess.QueryOver<Cat>()
.JoinAlias(c => c.Mate, () => mate)
.Select(c => c.AsEntity(), c => mate.Name)
.List<object[]>();]]></programlisting>
<para>
Or it can be done via the <literal>Projections.RootEntity</literal> and <literal>Projections.Entity</literal> methods
if more control over loaded entities is required. For instance, entity projections can be lazy loaded
or fetched with lazy properties:
</para>
<programlisting><![CDATA[.Select(
Projections.Entity(() => alias1).SetLazy(true),
Projections.Entity(() => alias2).SetFetchLazyProperties(true),
Projections.RootEntity()
)]]></programlisting>
</sect1>
<sect1 id="queryqueryover-subqueries">
<title>Sub-queries</title>
<para>
The Sub-queries factory class has overloads to allow Lambda Expressions to express sub-query
restrictions. For example:
</para>
<programlisting><![CDATA[QueryOver<Cat> maximumAge =
QueryOver.Of<Cat>()
.SelectList(p => p.SelectMax(c => c.Age));
IList<Cat> oldestCats =
session.QueryOver<Cat>()
.Where(Subqueries.WhereProperty<Cat>(c => c.Age).Eq(maximumAge))
.List();]]></programlisting>
<para> </para>
<para>
The inline syntax allows you to use sub-queries without re-qualifying the type:
</para>
<programlisting><![CDATA[IList<Cat> oldestCats =
session.QueryOver<Cat>()
.WithSubquery.WhereProperty(c => c.Age).Eq(maximumAge)
.List();]]></programlisting>
<para> </para>
<para>
There is an extension method <code>As()</code> on (a detached) QueryOver that allows you to cast it to any type.
This is used in conjunction with the overloads <code>Where(), WhereAll(),</code> and <code>WhereSome()</code>
to allow use of the built-in C# operators for comparison, so the above query can be written as:
</para>
<programlisting><![CDATA[IList<Cat> oldestCats =
session.QueryOver<Cat>()
.WithSubquery.Where(c => c.Age == maximumAge.As<int>())
.List();]]></programlisting>
</sect1>
</chapter>