-
-
Notifications
You must be signed in to change notification settings - Fork 41
/
SqlTable.cs
1903 lines (1461 loc) · 72.6 KB
/
SqlTable.cs
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 Max Toro Q.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.Linq.Mapping;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Text;
namespace DbExtensions {
/// <summary>
/// A non-generic version of <see cref="SqlTable<TEntity>"/> which can be used when the type of the entity is not known at build time.
/// This class cannot be instantiated, to get an instance use the <see cref="Database.Table(Type)"/> method.
/// </summary>
/// <seealso cref="Database.Table(Type)"/>
[DebuggerDisplay("{metaType.Name}")]
public sealed class SqlTable : SqlSet, ISqlTable {
// table is the SqlTable<TEntity> instance for metaType
// SqlTable is only a wrapper on SqlTable<TEntity>
readonly ISqlTable table;
readonly MetaType metaType;
readonly SqlCommandBuilder<object> sqlCommands;
/// <summary>
/// Gets a <see cref="SqlCommandBuilder<Object>"/> object for the current table.
/// </summary>
public SqlCommandBuilder<object> SQL {
get { return sqlCommands; }
}
internal static string ColumnList(MetaType metaType, IEnumerable<MetaDataMember> selectMembers, string tableAlias, Database db) {
if (selectMembers == null) {
selectMembers = metaType.PersistentDataMembers.Where(m => !m.IsAssociation);
}
var sb = new StringBuilder();
string qualifier = (!String.IsNullOrEmpty(tableAlias)) ?
db.QuoteIdentifier(tableAlias) + "." : null;
IEnumerator<MetaDataMember> enumerator = selectMembers.GetEnumerator();
while (enumerator.MoveNext()) {
string mappedName = enumerator.Current.MappedName;
string memberName = enumerator.Current.Name;
string columnAlias = !String.Equals(mappedName, memberName, StringComparison.Ordinal) ?
memberName : null;
if (sb.Length > 0) {
sb.Append(", ");
}
if (qualifier != null) {
sb.Append(qualifier);
}
sb.Append(db.QuoteIdentifier(enumerator.Current.MappedName));
if (columnAlias != null) {
sb.Append(" AS ")
.Append(db.QuoteIdentifier(memberName));
}
}
return sb.ToString();
}
internal static string TableName(MetaType metaType, string tableAlias, Database db) {
if (metaType.Table == null) throw new InvalidOperationException("metaType.Table cannot be null.");
string alias = (!String.IsNullOrEmpty(tableAlias)) ?
" " + db.QuoteIdentifier(tableAlias)
: null;
return db.QuoteIdentifier(metaType.Table.TableName) + (alias ?? "");
}
internal static void EnsureEntityType(MetaType metaType) {
if (!metaType.IsEntity) {
throw new InvalidOperationException(
String.Format(CultureInfo.InvariantCulture,
"The operation is not available for non-entity types ('{0}').", metaType.Type.FullName)
);
}
}
internal SqlTable(Database db, MetaType metaType, ISqlTable table)
: base(new string[2] { TableName(metaType, null, db), ColumnList(metaType, null, null, db) }, metaType.Type, db) {
this.table = table;
this.metaType = metaType;
this.sqlCommands = new SqlCommandBuilder<object>(db, metaType);
}
/// <summary>
/// Casts the current <see cref="SqlTable"/> to the generic <see cref="SqlTable<TEntity>"/> instance.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <returns>The <see cref="SqlTable<TEntity>"/> instance for <typeparamref name="TEntity"/>.</returns>
/// <exception cref="System.InvalidOperationException">The specified <typeparamref name="TEntity"/> is not valid for this instance.</exception>
public new SqlTable<TEntity> Cast<TEntity>() where TEntity : class {
if (typeof(TEntity) != this.metaType.Type) {
throw new InvalidOperationException("The specified type parameter is not valid for this instance.");
}
return (SqlTable<TEntity>)table;
}
/// <summary>
/// Casts the elements of the set to the specified type.
/// </summary>
/// <param name="resultType">The type to cast the elements of the set to.</param>
/// <returns>A new <see cref="SqlSet"/> that contains each element of the current set cast to the specified type.</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public new SqlSet Cast(Type resultType) {
return base.Cast(resultType);
}
#region ISqlTable Members
// These methods just call the same method on this.table
/// <summary>
/// Gets the entity whose primary key matches the <paramref name="id"/> parameter.
/// </summary>
/// <param name="id">The primary key value.</param>
/// <returns>
/// The entity whose primary key matches the <paramref name="id"/> parameter,
/// or null if the <paramref name="id"/> does not exist.
/// </returns>
public object Find(object id) {
return table.Find(id);
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entity"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entity">
/// The object whose INSERT command is to be executed. This parameter is named entity for consistency
/// with the other CRUD methods, but in this case it doesn't need to be an actual entity, which means it doesn't
/// need to have a primary key.
/// </param>
public void Add(object entity) {
table.Add(entity);
}
void ISqlTable.AddDescendants(object entity) {
table.AddDescendants(entity);
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entities"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entities">The entities whose INSERT commands are to be executed.</param>
public void AddRange(IEnumerable<object> entities) {
table.AddRange(entities);
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entities"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entities">The entities whose INSERT commands are to be executed.</param>
public void AddRange(params object[] entities) {
table.AddRange(entities);
}
/// <summary>
/// Executes an UPDATE command for the specified <paramref name="entity"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose UPDATE command is to be executed.</param>
public void Update(object entity) {
table.Update(entity);
}
/// <summary>
/// Executes an UPDATE command for the specified <paramref name="entity"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose UPDATE command is to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void Update(object entity, ConcurrencyConflictPolicy conflictPolicy) {
table.Update(entity, conflictPolicy);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
public void UpdateRange(IEnumerable<object> entities) {
table.UpdateRange(entities);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void UpdateRange(IEnumerable<object> entities, ConcurrencyConflictPolicy conflictPolicy) {
table.UpdateRange(entities, conflictPolicy);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
public void UpdateRange(params object[] entities) {
table.UpdateRange(entities);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void UpdateRange(object[] entities, ConcurrencyConflictPolicy conflictPolicy) {
table.UpdateRange(entities, conflictPolicy);
}
/// <summary>
/// Executes a DELETE command for the specified <paramref name="entity"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose DELETE command is to be executed.</param>
public void Remove(object entity) {
table.Remove(entity);
}
/// <summary>
/// Executes a DELETE command for the specified <paramref name="entity"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose DELETE command is to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void Remove(object entity, ConcurrencyConflictPolicy conflictPolicy) {
table.Remove(entity, conflictPolicy);
}
/// <summary>
/// Executes a DELETE command for the entity
/// whose primary key matches the <paramref name="id"/> parameter,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="id">The primary key value.</param>
public void RemoveKey(object id) {
table.RemoveKey(id);
}
/// <summary>
/// Executes a DELETE command for the entity
/// whose primary key matches the <paramref name="id"/> parameter,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="id">The primary key value.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies how to validate the affected records value.
/// </param>
public void RemoveKey(object id, ConcurrencyConflictPolicy conflictPolicy) {
table.RemoveKey(id, conflictPolicy);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
public void RemoveRange(IEnumerable<object> entities) {
table.RemoveRange(entities);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void RemoveRange(IEnumerable<object> entities, ConcurrencyConflictPolicy conflictPolicy) {
table.RemoveRange(entities, conflictPolicy);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
public void RemoveRange(params object[] entities) {
table.RemoveRange(entities);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void RemoveRange(object[] entities, ConcurrencyConflictPolicy conflictPolicy) {
table.RemoveRange(entities, conflictPolicy);
}
/// <summary>
/// Checks the existance of the <paramref name="entity"/>,
/// using the primary key value. Version members are ignored.
/// </summary>
/// <param name="entity">The entity whose existance is to be checked.</param>
/// <returns>true if the primary key value exists in the database; otherwise false.</returns>
public bool Contains(object entity) {
return table.Contains(entity);
}
/// <summary>
/// Checks the existance of the <paramref name="entity"/>,
/// using the primary key and optionally version column.
/// </summary>
/// <param name="entity">The entity whose existance is to be checked.</param>
/// <param name="version">true to check the version column; otherwise, false.</param>
/// <returns>true if the primary key and version combination exists in the database; otherwise, false.</returns>
public bool Contains(object entity, bool version) {
return table.Contains(entity, version);
}
/// <summary>
/// Checks the existance of an entity whose primary matches the <paramref name="id"/> parameter.
/// </summary>
/// <param name="id">The primary key value.</param>
/// <returns>true if the primary key value exists in the database; otherwise false.</returns>
public bool ContainsKey(object id) {
return table.ContainsKey(id);
}
/// <summary>
/// Sets all mapped members of <paramref name="entity"/> to their most current persisted value.
/// </summary>
/// <param name="entity">The entity to refresh.</param>
public void Refresh(object entity) {
table.Refresh(entity);
}
#endregion
}
/// <summary>
/// A <see cref="SqlSet<TEntity>"/> that provides additional methods for CRUD (Create, Read, Update, Delete)
/// operations for entities mapped using the <see cref="N:System.Data.Linq.Mapping"/> API.
/// This class cannot be instantiated, to get an instance use the <see cref="Database.Table<TEntity>"/> method.
/// </summary>
/// <typeparam name="TEntity">The type of the entity.</typeparam>
/// <seealso cref="Database.Table<TEntity>()"/>
[DebuggerDisplay("{metaType.Name}")]
public sealed class SqlTable<TEntity> : SqlSet<TEntity>, ISqlTable
where TEntity : class {
readonly Database db;
readonly MetaType metaType;
readonly SqlCommandBuilder<TEntity> sqlCommands;
/// <summary>
/// Gets a <see cref="SqlCommandBuilder<TEntity>"/> object for the current table.
/// </summary>
public SqlCommandBuilder<TEntity> SQL {
get { return sqlCommands; }
}
internal SqlTable(Database db, MetaType metaType)
: base(new string[2] { SqlTable.TableName(metaType, null, db), SqlTable.ColumnList(metaType, null, null, db) }, db) {
this.db = db;
this.metaType = metaType;
this.sqlCommands = new SqlCommandBuilder<TEntity>(db, metaType);
}
string QuoteIdentifier(string unquotedIdentifier) {
return this.db.QuoteIdentifier(unquotedIdentifier);
}
void EnsureEntityType() {
SqlTable.EnsureEntityType(metaType);
}
// CRUD
/// <summary>
/// Gets the entity whose primary key matches the <paramref name="id"/> parameter.
/// </summary>
/// <param name="id">The primary key value.</param>
/// <returns>
/// The entity whose primary key matches the <paramref name="id"/> parameter,
/// or null if the <paramref name="id"/> does not exist.
/// </returns>
public TEntity Find(object id) {
return Extensions.Find(this, id);
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entity"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entity">
/// The object whose INSERT command is to be executed. This parameter is named entity for consistency
/// with the other CRUD methods, but in this case it doesn't need to be an actual entity, which means it doesn't
/// need to have a primary key.
/// </param>
public void Add(TEntity entity) {
if (entity == null) throw new ArgumentNullException("entity");
SqlBuilder insertSql = this.SQL.INSERT_INTO_VALUES(entity);
MetaDataMember idMember = metaType.DBGeneratedIdentityMember;
MetaDataMember[] syncMembers =
(from m in metaType.PersistentDataMembers
where (m.AutoSync == AutoSync.Always || m.AutoSync == AutoSync.OnInsert)
&& m != idMember
select m).ToArray();
using (var tx = this.db.EnsureInTransaction()) {
// Transaction is required by SQLCE 4.0
// https://connect.microsoft.com/SQLServer/feedback/details/653675/sql-ce-4-0-select-identity-returns-null
this.db.AffectOne(insertSql);
if (idMember != null) {
object id = this.db.LastInsertId();
if (Convert.IsDBNull(id) || id == null) {
throw new DataException("The last insert id value cannot be null.");
}
object convertedId;
try {
convertedId = Convert.ChangeType(id, idMember.Type, CultureInfo.InvariantCulture);
} catch (InvalidCastException ex) {
throw new DataException("Couldn't convert the last insert id value to the appropiate type (see inner exception for details).", ex);
}
object entityObj = (object)entity;
idMember.MemberAccessor.SetBoxedValue(ref entityObj, convertedId);
}
if (syncMembers.Length > 0
&& metaType.IsEntity) {
Refresh(entity, syncMembers);
}
if (this.db.Configuration.EnableInsertRecursion) {
InsertDescendants(entity);
}
tx.Commit();
}
}
void InsertDescendants(TEntity entity) {
InsertOneToOne(entity);
InsertOneToMany(entity);
}
void InsertOneToOne(TEntity entity) {
MetaAssociation[] oneToOne = metaType.Associations
.Where(a => !a.IsMany && a.ThisKeyIsPrimaryKey && a.OtherKeyIsPrimaryKey)
.ToArray();
for (int i = 0; i < oneToOne.Length; i++) {
MetaAssociation assoc = oneToOne[i];
object child = assoc.ThisMember.MemberAccessor.GetBoxedValue(entity);
if (child == null) {
continue;
}
for (int j = 0; j < assoc.ThisKey.Count; j++) {
MetaDataMember thisKey = assoc.ThisKey[j];
MetaDataMember otherKey = assoc.OtherKey[j];
object thisKeyVal = thisKey.MemberAccessor.GetBoxedValue(entity);
otherKey.MemberAccessor.SetBoxedValue(ref child, thisKeyVal);
}
SqlTable otherTable = this.db.Table(assoc.OtherType);
otherTable.Add(child);
}
}
void InsertOneToMany(TEntity entity) {
MetaAssociation[] oneToMany = metaType.Associations.Where(a => a.IsMany).ToArray();
for (int i = 0; i < oneToMany.Length; i++) {
MetaAssociation assoc = oneToMany[i];
object[] many = ((IEnumerable<object>)assoc.ThisMember.MemberAccessor.GetBoxedValue(entity) ?? new object[0])
.Where(o => o != null)
.ToArray();
if (many.Length == 0) continue;
for (int j = 0; j < many.Length; j++) {
object child = many[j];
for (int k = 0; k < assoc.ThisKey.Count; k++) {
MetaDataMember thisKey = assoc.ThisKey[k];
MetaDataMember otherKey = assoc.OtherKey[k];
object thisKeyVal = thisKey.MemberAccessor.GetBoxedValue(entity);
otherKey.MemberAccessor.SetBoxedValue(ref child, thisKeyVal);
}
}
SqlTable otherTable = this.db.Table(assoc.OtherType);
otherTable.AddRange(many);
for (int j = 0; j < many.Length; j++) {
object child = many[j];
((ISqlTable)otherTable).AddDescendants(child);
}
}
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entities"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entities">The entities whose INSERT commands are to be executed.</param>
public void AddRange(IEnumerable<TEntity> entities) {
if (entities == null) throw new ArgumentNullException("entities");
AddRange(entities.ToArray());
}
/// <summary>
/// Recursively executes INSERT commands for the specified <paramref name="entities"/> and all it's
/// one-to-one and one-to-many associations. Recursion can be disabled by setting
/// <see cref="DatabaseConfiguration.EnableInsertRecursion"/> to false.
/// </summary>
/// <param name="entities">The entities whose INSERT commands are to be executed.</param>
public void AddRange(params TEntity[] entities) {
if (entities == null) throw new ArgumentNullException("entities");
entities = entities.Where(o => o != null).ToArray();
if (entities.Length == 0) {
return;
}
if (entities.Length == 1) {
Add(entities[0]);
return;
}
MetaDataMember[] syncMembers =
(from m in metaType.PersistentDataMembers
where (m.AutoSync == AutoSync.Always || m.AutoSync == AutoSync.OnInsert)
select m).ToArray();
bool batch = syncMembers.Length == 0
&& this.db.Configuration.EnableBatchCommands;
if (batch) {
SqlBuilder batchInsert = SqlBuilder.JoinSql(";" + Environment.NewLine, entities.Select(e => this.SQL.INSERT_INTO_VALUES(e)));
using (var tx = this.db.EnsureInTransaction()) {
this.db.Affect(batchInsert, entities.Length, AffectedRecordsPolicy.MustMatchAffecting);
if (this.db.Configuration.EnableInsertRecursion) {
for (int i = 0; i < entities.Length; i++) {
InsertDescendants(entities[i]);
}
}
tx.Commit();
}
} else {
using (var tx = this.db.EnsureInTransaction()) {
for (int i = 0; i < entities.Length; i++) {
Add(entities[i]);
}
tx.Commit();
}
}
}
/// <summary>
/// Executes an UPDATE command for the specified <paramref name="entity"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose UPDATE command is to be executed.</param>
public void Update(TEntity entity) {
Update(entity, this.db.Configuration.UpdateConflictPolicy);
}
/// <summary>
/// Executes an UPDATE command for the specified <paramref name="entity"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose UPDATE command is to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void Update(TEntity entity, ConcurrencyConflictPolicy conflictPolicy) {
if (entity == null) throw new ArgumentNullException("entity");
SqlBuilder updateSql = this.SQL.UPDATE_SET_WHERE(entity, conflictPolicy);
AffectedRecordsPolicy affRec = GetAffectedRecordsPolicy(conflictPolicy);
MetaDataMember[] syncMembers =
(from m in metaType.PersistentDataMembers
where m.AutoSync == AutoSync.Always || m.AutoSync == AutoSync.OnUpdate
select m).ToArray();
using (this.db.EnsureConnectionOpen()) {
this.db.Affect(updateSql, 1, affRec);
if (syncMembers.Length > 0) {
Refresh(entity, syncMembers);
}
}
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
public void UpdateRange(IEnumerable<TEntity> entities) {
if (entities == null) throw new ArgumentNullException("entities");
UpdateRange(entities.ToArray());
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void UpdateRange(IEnumerable<TEntity> entities, ConcurrencyConflictPolicy conflictPolicy) {
if (entities == null) throw new ArgumentNullException("entities");
UpdateRange(entities.ToArray(), conflictPolicy);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
public void UpdateRange(params TEntity[] entities) {
UpdateRange(entities, this.db.Configuration.UpdateConflictPolicy);
}
/// <summary>
/// Executes UPDATE commands for the specified <paramref name="entities"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose UPDATE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the UPDATE
/// predicate, and how to validate the affected records value.
/// </param>
public void UpdateRange(TEntity[] entities, ConcurrencyConflictPolicy conflictPolicy) {
if (entities == null) throw new ArgumentNullException("entities");
entities = entities.Where(o => o != null).ToArray();
if (entities.Length == 0) {
return;
}
if (entities.Length == 1) {
Update(entities[0], conflictPolicy);
return;
}
EnsureEntityType();
MetaDataMember[] syncMembers =
(from m in metaType.PersistentDataMembers
where m.AutoSync == AutoSync.Always || m.AutoSync == AutoSync.OnUpdate
select m).ToArray();
bool batch = syncMembers.Length == 0
&& this.db.Configuration.EnableBatchCommands;
if (batch) {
SqlBuilder batchUpdate = SqlBuilder.JoinSql(";" + Environment.NewLine, entities.Select(e => this.SQL.UPDATE_SET_WHERE(e, conflictPolicy)));
AffectedRecordsPolicy affRec = GetAffectedRecordsPolicy(conflictPolicy);
this.db.Affect(batchUpdate, entities.Length, affRec);
} else {
using (var tx = this.db.EnsureInTransaction()) {
for (int i = 0; i < entities.Length; i++) {
Update(entities[i], conflictPolicy);
}
tx.Commit();
}
}
}
/// <summary>
/// Executes a DELETE command for the specified <paramref name="entity"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose DELETE command is to be executed.</param>
public void Remove(TEntity entity) {
Remove(entity, this.db.Configuration.DeleteConflictPolicy);
}
/// <summary>
/// Executes a DELETE command for the specified <paramref name="entity"/>
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entity">The entity whose DELETE command is to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void Remove(TEntity entity, ConcurrencyConflictPolicy conflictPolicy) {
if (entity == null) throw new ArgumentNullException("entity");
AffectedRecordsPolicy affRec = GetAffectedRecordsPolicy(conflictPolicy);
this.db.Affect(this.SQL.DELETE_FROM_WHERE(entity, conflictPolicy), 1, affRec);
}
/// <summary>
/// Executes a DELETE command for the entity
/// whose primary key matches the <paramref name="id"/> parameter,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="id">The primary key value.</param>
public void RemoveKey(object id) {
RemoveKey(id, this.db.Configuration.DeleteConflictPolicy);
}
/// <summary>
/// Executes a DELETE command for the entity
/// whose primary key matches the <paramref name="id"/> parameter,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="id">The primary key value.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies how to validate the affected records value.
/// </param>
public void RemoveKey(object id, ConcurrencyConflictPolicy conflictPolicy) {
this.db.Affect(this.SQL.DELETE_FROM_WHERE_id(id), 1, GetAffectedRecordsPolicy(conflictPolicy));
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
public void RemoveRange(IEnumerable<TEntity> entities) {
if (entities == null) throw new ArgumentNullException("entities");
RemoveRange(entities.ToArray());
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void RemoveRange(IEnumerable<TEntity> entities, ConcurrencyConflictPolicy conflictPolicy) {
if (entities == null) throw new ArgumentNullException("entities");
RemoveRange(entities.ToArray(), conflictPolicy);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the default <see cref="ConcurrencyConflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
public void RemoveRange(params TEntity[] entities) {
RemoveRange(entities, this.db.Configuration.DeleteConflictPolicy);
}
/// <summary>
/// Executes DELETE commands for the specified <paramref name="entities"/>,
/// using the provided <paramref name="conflictPolicy"/>.
/// </summary>
/// <param name="entities">The entities whose DELETE commands are to be executed.</param>
/// <param name="conflictPolicy">
/// The <see cref="ConcurrencyConflictPolicy"/> that specifies what columns to check for in the DELETE
/// predicate, and how to validate the affected records value.
/// </param>
public void RemoveRange(TEntity[] entities, ConcurrencyConflictPolicy conflictPolicy) {
if (entities == null) throw new ArgumentNullException("entities");
entities = entities.Where(o => o != null).ToArray();
if (entities.Length == 0) {
return;
}
if (entities.Length == 1) {
Remove(entities[0], conflictPolicy);
return;
}
EnsureEntityType();
AffectedRecordsPolicy affRec = GetAffectedRecordsPolicy(conflictPolicy);
bool useVersion = conflictPolicy == ConcurrencyConflictPolicy.UseVersion
&& this.metaType.VersionMember != null;
bool singleStatement = this.metaType.IdentityMembers.Count == 1
&& !useVersion;
bool batch = this.db.Configuration.EnableBatchCommands;
if (singleStatement) {
MetaDataMember idMember = this.metaType.IdentityMembers[0];
object[] ids = entities.Select(e => this.SQL.GetMemberValue(e, idMember)).ToArray();
SqlBuilder sql = this.SQL
.DELETE_FROM()
.WHERE(this.db.QuoteIdentifier(idMember.MappedName) + " IN ({0})", new object[1] { ids });
this.db.Affect(sql, entities.Length, affRec);
} else if (batch) {
SqlBuilder batchDelete = SqlBuilder.JoinSql(";" + Environment.NewLine, entities.Select(e => this.SQL.DELETE_FROM_WHERE(e, conflictPolicy)));
this.db.Affect(batchDelete, entities.Length, affRec);
} else {
using (var tx = this.db.EnsureInTransaction()) {
for (int i = 0; i < entities.Length; i++) {
Remove(entities[i], conflictPolicy);
}
tx.Commit();
}
}
}
static AffectedRecordsPolicy GetAffectedRecordsPolicy(ConcurrencyConflictPolicy conflictPolicy) {
switch (conflictPolicy) {
case ConcurrencyConflictPolicy.UseVersion:
case ConcurrencyConflictPolicy.IgnoreVersion:
return AffectedRecordsPolicy.MustMatchAffecting;
case ConcurrencyConflictPolicy.IgnoreVersionAndLowerAffectedRecords:
return AffectedRecordsPolicy.AllowLower;
default:
throw new ArgumentOutOfRangeException("conflictPolicy");
}
}
// Misc
/// <summary>
/// Checks the existance of the <paramref name="entity"/>,
/// using the primary key value. Version members are ignored.
/// </summary>
/// <param name="entity">The entity whose existance is to be checked.</param>
/// <returns>true if the primary key value exists in the database; otherwise false.</returns>
public bool Contains(TEntity entity) {
return Contains(entity, version: false);
}
/// <summary>
/// Checks the existance of the <paramref name="entity"/>,
/// using the primary key and optionally version column.
/// </summary>
/// <param name="entity">The entity whose existance is to be checked.</param>
/// <param name="version">true to check the version column; otherwise, false.</param>
/// <returns>true if the primary key and version combination exists in the database; otherwise, false.</returns>
public bool Contains(TEntity entity, bool version) {
if (entity == null) throw new ArgumentNullException("entity");
EnsureEntityType();
MetaDataMember[] predicateMembers =
(from m in metaType.PersistentDataMembers
where m.IsPrimaryKey || (m.IsVersion && version)
select m).ToArray();