Repository navigation
Expand file tree
/
Copy pathMappedMetaModel.cs
More file actions
1829 lines (1733 loc) · 76.5 KB
/
Copy pathMappedMetaModel.cs
File metadata and controls
1829 lines (1733 loc) · 76.5 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Linq;
using System.Data.Linq.Provider;
using System.Data.Linq.Mapping;
using System.Data.Linq.SqlClient;
using System.Threading;
using System.Runtime.Versioning;
using LinqToSqlShared.Mapping;
using System.Runtime.CompilerServices;
namespace System.Data.Linq.Mapping {
internal class MappedMetaModel : MetaModel {
ReaderWriterLock @lock = new ReaderWriterLock();
MappingSource mappingSource;
Type contextType;
Type providerType;
DatabaseMapping mapping;
HashSet<Module> modules;
Dictionary<string, Type> types;
Dictionary<Type, MetaType> metaTypes;
Dictionary<Type, MetaTable> metaTables;
Dictionary<MetaPosition, MetaFunction> metaFunctions;
bool fullyLoaded;
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // mapping parameter contains various type references.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
internal MappedMetaModel(MappingSource mappingSource, Type contextType, DatabaseMapping mapping) {
this.mappingSource = mappingSource;
this.contextType = contextType;
this.mapping = mapping;
this.modules = new HashSet<Module>();
this.modules.Add(this.contextType.Module);
this.metaTypes = new Dictionary<Type, MetaType>();
this.metaTables = new Dictionary<Type, MetaTable>();
this.types = new Dictionary<string, Type>();
// Provider type
if (this.providerType == null && !String.IsNullOrEmpty(this.mapping.Provider)) {
this.providerType = this.FindType(this.mapping.Provider, typeof(SqlProvider).Namespace);
if (this.providerType == null) {
throw Error.ProviderTypeNotFound(this.mapping.Provider);
}
}
else if (this.providerType == null) {
this.providerType = typeof(SqlProvider);
}
this.Init();
}
#region Initialization
private void Init() {
if (!fullyLoaded) {
// The fullyLoaded state is required so that tools like
// CreateDatabase can get a full view of all tables.
@lock.AcquireWriterLock(Timeout.Infinite);
try {
if (!fullyLoaded) {
// Initialize static tables and functions.
this.InitStaticTables();
this.InitFunctions();
fullyLoaded = true;
}
}
finally {
@lock.ReleaseWriterLock();
}
}
}
[ResourceExposure(ResourceScope.None)] // Exposure is via external mapping file/attributes.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine, ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
private void InitStaticTables() {
this.InitStaticTableTypes();
foreach (TableMapping tableMapping in this.mapping.Tables) {
Type rowType = this.FindType(tableMapping.RowType.Name);
if (rowType == null) {
throw Error.CouldNotFindTypeFromMapping(tableMapping.RowType.Name);
}
Type rootType = this.GetRootType(rowType, tableMapping.RowType);
MetaTable table = new MappedTable(this, tableMapping, rootType);
foreach (MetaType mt in table.RowType.InheritanceTypes) {
this.metaTypes.Add(mt.Type, mt);
this.metaTables.Add(mt.Type, table);
}
}
}
private void InitStaticTableTypes() {
for (Type type = this.contextType; type != typeof(DataContext); type = type.BaseType) {
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (FieldInfo fi in fields) {
Type ft = fi.FieldType;
if (ft.IsGenericType && ft.GetGenericTypeDefinition() == typeof(Table<>)) {
Type rowType = ft.GetGenericArguments()[0];
if (!this.types.ContainsKey(rowType.Name)) {
this.types.Add(rowType.FullName, rowType);
if (!this.types.ContainsKey(rowType.Name)) {
this.types.Add(rowType.Name, rowType);
}
this.modules.Add(rowType.Module);
}
}
}
PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
foreach (PropertyInfo pi in props) {
Type pt = pi.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Table<>)) {
Type rowType = pt.GetGenericArguments()[0];
if (!this.types.ContainsKey(rowType.Name)) {
this.types.Add(rowType.FullName, rowType);
if (!this.types.ContainsKey(rowType.Name)) {
this.types.Add(rowType.Name, rowType);
}
this.modules.Add(rowType.Module);
}
}
}
}
}
[ResourceExposure(ResourceScope.None)] // mapping instance variable is set elsewhere.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine, ResourceScope.Assembly | ResourceScope.Machine)] // For GetMethods call.
private void InitFunctions() {
this.metaFunctions = new Dictionary<MetaPosition, MetaFunction>();
if (this.contextType != typeof(DataContext)) {
foreach (FunctionMapping fmap in this.mapping.Functions) {
MethodInfo method = this.GetMethod(fmap.MethodName);
if (method == null) {
throw Error.MethodCannotBeFound(fmap.MethodName);
}
MappedFunction func = new MappedFunction(this, fmap, method);
this.metaFunctions.Add(new MetaPosition(method), func);
// pre-set all known function result types into metaType map
foreach (MetaType rt in func.ResultRowTypes) {
foreach (MetaType it in rt.InheritanceTypes) {
if (!this.metaTypes.ContainsKey(it.Type)) {
this.metaTypes.Add(it.Type, it);
}
}
}
}
}
}
#endregion
public override MappingSource MappingSource {
get { return this.mappingSource; }
}
public override Type ContextType {
get { return this.contextType; }
}
public override string DatabaseName {
get { return this.mapping.DatabaseName; }
}
public override Type ProviderType {
get { return this.providerType; }
}
public override IEnumerable<MetaTable> GetTables() {
return this.metaTables.Values.Where(x => x != null).Distinct();
}
public override MetaTable GetTable(Type rowType) {
if (rowType == null) {
throw Error.ArgumentNull("rowType");
}
MetaTable table = null;
this.metaTables.TryGetValue(rowType, out table);
return table;
}
public override MetaType GetMetaType(Type type) {
if (type == null) {
throw Error.ArgumentNull("type");
}
MetaType mtype = null;
@lock.AcquireReaderLock(Timeout.Infinite);
try {
if (this.metaTypes.TryGetValue(type, out mtype)) {
return mtype;
}
}
finally {
@lock.ReleaseReaderLock();
}
@lock.AcquireWriterLock(Timeout.Infinite);
try {
if (!this.metaTypes.TryGetValue(type, out mtype)) {
// not known, so must be unmapped type
mtype = new UnmappedType(this, type);
this.metaTypes.Add(type, mtype);
}
}
finally {
@lock.ReleaseWriterLock();
}
return mtype;
}
public override MetaFunction GetFunction(MethodInfo method) {
if (method == null) {
throw new ArgumentNullException("method");
}
MetaFunction func = null;
this.metaFunctions.TryGetValue(new MetaPosition(method), out func);
return func;
}
public override IEnumerable<MetaFunction> GetFunctions() {
return this.metaFunctions.Values;
}
private Type GetRootType(Type type, TypeMapping rootMapping) {
if (string.Compare(rootMapping.Name, type.Name, StringComparison.Ordinal) == 0
|| string.Compare(rootMapping.Name, type.FullName, StringComparison.Ordinal) == 0
|| string.Compare(rootMapping.Name, type.AssemblyQualifiedName, StringComparison.Ordinal) == 0)
return type;
if (type.BaseType != typeof(object)) {
return this.GetRootType(type.BaseType, rootMapping);
}
throw Error.UnableToResolveRootForType(type);
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter will be found on a type.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
private MethodInfo GetMethod(string name) {
string typeName, methodName;
this.GetTypeAndMethod(name, out typeName, out methodName);
Type type = this.FindType(typeName);
if (type != null) {
return type.GetMethod(methodName, BindingFlags.Instance|BindingFlags.Public|BindingFlags.NonPublic);
}
return null;
}
private void GetTypeAndMethod(string name, out string typeName, out string methodName) {
int dotIndex = name.LastIndexOf(".", StringComparison.CurrentCulture);
if (dotIndex > 0) {
typeName = name.Substring(0, dotIndex);
methodName = name.Substring(dotIndex + 1);
}
else {
typeName = this.contextType.FullName;
methodName = name;
}
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
internal Type FindType(string name) {
return this.FindType(name, this.contextType.Namespace);
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // SearchForType method call.
internal Type FindType(string name, string defaultNamespace) {
Type result = null;
string name2 = null;
@lock.AcquireReaderLock(Timeout.Infinite);
try {
if (this.types.TryGetValue(name, out result)) {
return result;
}
name2 = name.Contains(".") ? null : defaultNamespace + "." + name;
if (name2 != null && this.types.TryGetValue(name2, out result)) {
return result;
}
}
finally {
@lock.ReleaseReaderLock();
}
// don't block anyone while we search for the correct type
Type foundResult = this.SearchForType(name);
if (foundResult == null && name2 != null) {
foundResult = this.SearchForType(name2);
}
if (foundResult != null) {
@lock.AcquireWriterLock(Timeout.Infinite);
try {
if (this.types.TryGetValue(name, out result)) {
return result;
}
this.types.Add(name, foundResult);
return foundResult;
}
finally {
@lock.ReleaseWriterLock();
}
}
return null;
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // SearchForType method call.
private Type SearchForType(string name) {
// Try search for type using case sensitive.
Type type = SearchForType(name, false);
if (type != null) {
return type;
}
// Try search for type using case in-sensitive.
return SearchForType(name, true);
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // name parameter is a type name.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // Assembly.GetLoadedModules method call.
private Type SearchForType(string name, bool ignoreCase) {
// first try default system lookup
Type type = Type.GetType(name, false, ignoreCase);
if (type != null) {
return type;
}
// try all known modules (modules that other statically known types were found in)
foreach (Module module in this.modules) {
type = module.GetType(name, false, ignoreCase);
if (type != null) {
return type;
}
}
// try all loaded modules (is there a better way?)
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
foreach (Module module in a.GetLoadedModules()) {
type = module.GetType(name, false, ignoreCase);
if (type != null) {
return type;
}
}
}
return null;
}
}
internal sealed class MappedTable : MetaTable {
MappedMetaModel model;
TableMapping mapping;
MetaType rowType;
bool hasMethods;
MethodInfo insertMethod;
MethodInfo updateMethod;
MethodInfo deleteMethod;
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // Parameter contains various type references.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // MappedRootType constructor call.
internal MappedTable(MappedMetaModel model, TableMapping mapping, Type rowType) {
this.model = model;
this.mapping = mapping;
this.rowType = new MappedRootType(model, this, mapping.RowType, rowType);
}
public override MetaModel Model {
get { return this.model; }
}
public override string TableName {
get { return this.mapping.TableName; }
}
public override MetaType RowType {
get { return this.rowType; }
}
public override MethodInfo InsertMethod {
get {
this.InitMethods();
return this.insertMethod;
}
}
public override MethodInfo UpdateMethod {
get {
this.InitMethods();
return this.updateMethod;
}
}
public override MethodInfo DeleteMethod {
get {
this.InitMethods();
return this.deleteMethod;
}
}
private void InitMethods() {
if (!this.hasMethods) {
this.insertMethod = MethodFinder.FindMethod(
this.model.ContextType,
"Insert" + rowType.Name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
new Type[] { rowType.Type }
);
this.updateMethod = MethodFinder.FindMethod(
this.model.ContextType,
"Update" + rowType.Name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
new Type[] { rowType.Type }
);
this.deleteMethod = MethodFinder.FindMethod(
this.model.ContextType,
"Delete" + rowType.Name,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
new Type[] { rowType.Type }
);
this.hasMethods = true;
}
}
}
internal sealed class MappedRootType : MappedType {
Dictionary<Type, MetaType> derivedTypes;
Dictionary<object, MetaType> inheritanceCodes;
ReadOnlyCollection<MetaType> inheritanceTypes;
MetaType inheritanceDefault;
bool hasInheritance;
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // Various parameters can contain type names.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // InitInheritedType method call.
public MappedRootType(MappedMetaModel model, MappedTable table, TypeMapping typeMapping, Type type)
: base(model, table, typeMapping, type, null) {
if (typeMapping == null)
throw Error.ArgumentNull("typeMapping");
if (typeMapping.InheritanceCode != null || typeMapping.DerivedTypes.Count > 0) {
if (this.Discriminator == null) {
throw Error.NoDiscriminatorFound(type.Name);
}
this.hasInheritance = true;
if (!MappingSystem.IsSupportedDiscriminatorType(this.Discriminator.Type)) {
throw Error.DiscriminatorClrTypeNotSupported(this.Discriminator.DeclaringType.Name, this.Discriminator.Name, this.Discriminator.Type);
}
this.derivedTypes = new Dictionary<Type, MetaType>();
this.inheritanceCodes = new Dictionary<object, MetaType>();
this.InitInheritedType(typeMapping, this);
}
if (this.inheritanceDefault == null && (this.inheritanceCode != null || this.inheritanceCodes != null && this.inheritanceCodes.Count > 0))
throw Error.InheritanceHierarchyDoesNotDefineDefault(type);
if (this.derivedTypes != null) {
this.inheritanceTypes = this.derivedTypes.Values.ToList().AsReadOnly();
}
else {
this.inheritanceTypes = new MetaType[] { this }.ToList().AsReadOnly();
}
this.Validate();
}
private void Validate() {
Dictionary<object, string> memberToColumn = new Dictionary<object, string>();
foreach (MetaType type in this.InheritanceTypes) {
// NB: Table node in XML can have only one Type node -- enforced by XSD
foreach (MetaDataMember mem in type.PersistentDataMembers) {
if (mem.IsDeclaredBy(type)) {
if (mem.IsDiscriminator && !this.HasInheritance) {
throw Error.NonInheritanceClassHasDiscriminator(type);
}
if (!mem.IsAssociation) {
// validate that no database column is mapped twice
if (!string.IsNullOrEmpty(mem.MappedName)) {
string column;
object dn = InheritanceRules.DistinguishedMemberName(mem.Member);
if (memberToColumn.TryGetValue(dn, out column)) {
if (column != mem.MappedName) {
throw Error.MemberMappedMoreThanOnce(mem.Member.Name);
}
}
else {
memberToColumn.Add(dn, mem.MappedName);
}
}
}
}
}
}
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // typeMap parameter's Name property.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // FindType method call.
private MetaType InitDerivedTypes(TypeMapping typeMap) {
Type type = ((MappedMetaModel)Model).FindType(typeMap.Name);
if (type == null)
throw Error.CouldNotFindRuntimeTypeForMapping(typeMap.Name);
MappedType rowType = new MappedType(this.Model, this.Table, typeMap, type, this);
return this.InitInheritedType(typeMap, rowType);
}
[ResourceExposure(ResourceScope.Assembly | ResourceScope.Machine)] // typeMap parameter's Name property.
[ResourceConsumption(ResourceScope.Assembly | ResourceScope.Machine)] // InitDerivedTypes method call.
private MetaType InitInheritedType(TypeMapping typeMap, MappedType type) {
this.derivedTypes.Add(type.Type, type);
if (typeMap.InheritanceCode != null) { // Mapping with no inheritance code: For example, an unmapped intermediate class in a hierarchy.
if (this.Discriminator == null)
throw Error.NoDiscriminatorFound(type.Name);
if (type.Type.IsAbstract)
throw Error.AbstractClassAssignInheritanceDiscriminator(type.Type);
object keyValue = DBConvert.ChangeType(typeMap.InheritanceCode, this.Discriminator.Type);
foreach (object d in inheritanceCodes.Keys) {
// if the keys are equal, or if they are both strings containing only spaces
// they are considered equal
if ((keyValue.GetType() == typeof(string) && ((string)keyValue).Trim().Length == 0 &&
d.GetType() == typeof(string) && ((string)d).Trim().Length == 0) ||
object.Equals(d, keyValue)) {
throw Error.InheritanceCodeUsedForMultipleTypes(keyValue);
}
}
if (type.inheritanceCode != null)
throw Error.InheritanceTypeHasMultipleDiscriminators(type);
type.inheritanceCode = keyValue;
this.inheritanceCodes.Add(keyValue, type);
if (typeMap.IsInheritanceDefault) {
if (this.inheritanceDefault != null)
throw Error.InheritanceTypeHasMultipleDefaults(type);
this.inheritanceDefault = type;
}
}
// init sub-inherited types
foreach (TypeMapping tm in typeMap.DerivedTypes) {
this.InitDerivedTypes(tm);
}
return type;
}
public override bool HasInheritance {
get { return this.hasInheritance; }
}
public override bool HasInheritanceCode {
get { return this.InheritanceCode != null; }
}
public override ReadOnlyCollection<MetaType> InheritanceTypes {
get { return this.inheritanceTypes; }
}
public override MetaType GetInheritanceType(Type type) {
if (type == this.Type)
return this;
MetaType metaType = null;
if (this.derivedTypes != null) {
this.derivedTypes.TryGetValue(type, out metaType);
}
return metaType;
}
public override MetaType InheritanceDefault {
get { return this.inheritanceDefault; }
}
}
internal class MappedType : MetaType {
MetaModel model;
MetaTable table;
Type type;
TypeMapping typeMapping;
Dictionary<object, MetaDataMember> dataMemberMap;
ReadOnlyCollection<MetaDataMember> dataMembers;
ReadOnlyCollection<MetaDataMember> persistentDataMembers;
ReadOnlyCollection<MetaDataMember> identities;
MetaDataMember dbGeneratedIdentity;
MetaDataMember version;
MetaDataMember discriminator;
MetaType inheritanceRoot;
bool inheritanceBaseSet;
MetaType inheritanceBase;
internal object inheritanceCode;
ReadOnlyCollection<MetaType> derivedTypes;
ReadOnlyCollection<MetaAssociation> associations;
bool hasMethods;
bool hasAnyLoadMethod;
bool hasAnyValidateMethod;
MethodInfo onLoadedMethod;
MethodInfo onValidateMethod;
object locktarget = new object(); // Hold locks on private object rather than public MetaType.
internal MappedType(MetaModel model, MetaTable table, TypeMapping typeMapping, Type type, MetaType inheritanceRoot) {
this.model = model;
this.table = table;
this.typeMapping = typeMapping;
this.type = type;
this.inheritanceRoot = inheritanceRoot != null ? inheritanceRoot : this;
this.InitDataMembers();
this.identities = this.dataMembers.Where(m => m.IsPrimaryKey).ToList().AsReadOnly();
this.persistentDataMembers = this.dataMembers.Where(m => m.IsPersistent).ToList().AsReadOnly();
}
#region Initialization
private void ValidatePrimaryKeyMember(MetaDataMember mm) {
//if the type is a sub-type, no member in the type can be primary key
if (mm.IsPrimaryKey && this.inheritanceRoot != this && mm.Member.DeclaringType == this.type) {
throw (Error.PrimaryKeyInSubTypeNotSupported(this.type.Name, mm.Name));
}
}
private void InitMethods() {
if (!this.hasMethods) {
this.onLoadedMethod = MethodFinder.FindMethod(
this.Type,
"OnLoaded",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
Type.EmptyTypes,
false
);
this.onValidateMethod = MethodFinder.FindMethod(
this.Type,
"OnValidate",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
new[] { typeof(ChangeAction) },
false
);
this.hasAnyLoadMethod = (this.onLoadedMethod != null) || (this.InheritanceBase != null && this.InheritanceBase.HasAnyLoadMethod);
this.hasAnyValidateMethod = (this.onValidateMethod != null) || (this.InheritanceBase != null && this.InheritanceBase.HasAnyValidateMethod);
this.hasMethods = true;
}
}
private void InitDataMembers() {
if (this.dataMembers == null) {
Dictionary<object, MetaDataMember> map = new Dictionary<object, MetaDataMember>();
List<MetaDataMember> dMembers = new List<MetaDataMember>();
int ordinal = 0;
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy;
// Map of valid mapped names.
Dictionary<string, MemberMapping> names = new Dictionary<string, MemberMapping>();
Type currentType = this.type;
for (TypeMapping tm = this.typeMapping; tm != null; tm = tm.BaseType) {
foreach (MemberMapping mmap in tm.Members) {
names[mmap.MemberName + ":" + currentType.Name] = mmap;
}
currentType = currentType.BaseType;
}
HashSet<string> namesSeen = new HashSet<string>(); // Keep track of which names from the mapping file have been seen.
FieldInfo[] fis = TypeSystem.GetAllFields(this.type, flags).ToArray();
if (fis != null) {
foreach (FieldInfo fi in fis) {
MemberMapping mmap;
string name = fi.Name + ":" + fi.DeclaringType.Name;
if (names.TryGetValue(name, out mmap)) {
namesSeen.Add(name);
object dn = InheritanceRules.DistinguishedMemberName(fi);
MetaDataMember mm;
if (!map.TryGetValue(dn, out mm)) {
mm = new MappedDataMember(this, fi, mmap, ordinal);
map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
dMembers.Add(mm);
this.InitSpecialMember(mm);
}
ValidatePrimaryKeyMember(mm);
ordinal++;
}
}
}
PropertyInfo[] pis = TypeSystem.GetAllProperties(this.type, flags).ToArray();
if (pis != null) {
foreach (PropertyInfo pi in pis) {
MemberMapping mmap;
string name = pi.Name + ":" + pi.DeclaringType.Name;
if (names.TryGetValue(name, out mmap)) {
namesSeen.Add(name);
MetaDataMember mm;
object dn = InheritanceRules.DistinguishedMemberName(pi);
if (!map.TryGetValue(dn, out mm)) {
mm = new MappedDataMember(this, pi, mmap, ordinal);
map.Add(InheritanceRules.DistinguishedMemberName(mm.Member), mm);
dMembers.Add(mm);
this.InitSpecialMember(mm);
}
ValidatePrimaryKeyMember(mm);
ordinal++;
}
}
}
this.dataMembers = dMembers.AsReadOnly();
this.dataMemberMap = map;
// Finally, make sure that all types in the mapping file were consumed.
foreach(string name in namesSeen) {
names.Remove(name);
}
foreach(var orphan in names) {
Type aboveRoot = inheritanceRoot.Type.BaseType;
while (aboveRoot!=null) {
foreach(MemberInfo mi in aboveRoot.GetMembers(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
if(String.Compare(mi.Name, orphan.Value.MemberName, StringComparison.Ordinal)==0) {
throw Error.MappedMemberHadNoCorrespondingMemberInType(orphan.Value.MemberName, type.Name);
}
}
aboveRoot = aboveRoot.BaseType;
}
}
}
}
private void InitSpecialMember(MetaDataMember mm) {
// Can only have one auto gen member that is also an identity member,
// except if that member is a computed column (since they are implicitly auto gen)
if (mm.IsDbGenerated && mm.IsPrimaryKey && string.IsNullOrEmpty(mm.Expression)) {
if (this.dbGeneratedIdentity != null) {
throw Error.TwoMembersMarkedAsPrimaryKeyAndDBGenerated(mm.Member, this.dbGeneratedIdentity.Member);
}
this.dbGeneratedIdentity = mm;
}
if (mm.IsPrimaryKey && !MappingSystem.IsSupportedIdentityType(mm.Type))
{
throw Error.IdentityClrTypeNotSupported(mm.DeclaringType, mm.Name, mm.Type);
}
if (mm.IsVersion) {
if (this.version != null) {
throw Error.TwoMembersMarkedAsRowVersion(mm.Member, this.version.Member);
}
this.version = mm;
}
if (mm.IsDiscriminator) {
if (this.discriminator != null) {
if (!InheritanceRules.AreSameMember(this.discriminator.Member, mm.Member)) {
throw Error.TwoMembersMarkedAsInheritanceDiscriminator(mm.Member, this.discriminator.Member);
}
}
else {
this.discriminator = mm;
}
}
}
#endregion
public override MetaModel Model {
get { return this.model; }
}
public override MetaTable Table {
get { return this.table; }
}
public override Type Type {
get { return this.type; }
}
public override string Name {
get { return this.type.Name; }
}
public override bool IsEntity {
get {
if (this.table != null) {
return table.RowType.IdentityMembers.Count > 0;
}
return false;
}
}
public override bool CanInstantiate {
get { return !this.type.IsAbstract && (this == this.InheritanceRoot || this.HasInheritanceCode); }
}
public override MetaDataMember DBGeneratedIdentityMember {
get { return this.dbGeneratedIdentity; }
}
public override MetaDataMember VersionMember {
get { return this.version; }
}
public override MetaDataMember Discriminator {
get { return this.discriminator; }
}
public override bool HasUpdateCheck {
get {
foreach (MetaDataMember member in this.PersistentDataMembers) {
if (member.UpdateCheck != UpdateCheck.Never) {
return true;
}
}
return false;
}
}
public override bool HasInheritance {
get { return this.inheritanceRoot.HasInheritance; }
}
public override object InheritanceCode {
get { return this.inheritanceCode; }
}
public override bool HasInheritanceCode {
get { return this.InheritanceCode != null; }
}
public override bool IsInheritanceDefault {
get { return this.InheritanceDefault == this; }
}
public override MetaType InheritanceDefault {
get {
if (this.inheritanceRoot == this)
throw Error.CannotGetInheritanceDefaultFromNonInheritanceClass();
return this.InheritanceRoot.InheritanceDefault;
}
}
public override MetaType InheritanceRoot {
get { return this.inheritanceRoot; }
}
public override MetaType InheritanceBase {
get {
// LOCKING: Cannot initialize at construction
if (!this.inheritanceBaseSet && this.inheritanceBase == null) {
lock (this.locktarget) {
if (this.inheritanceBase == null) {
this.inheritanceBase = InheritanceBaseFinder.FindBase(this);
this.inheritanceBaseSet = true;
}
}
}
return this.inheritanceBase;
}
}
public override ReadOnlyCollection<MetaType> InheritanceTypes {
get { return this.inheritanceRoot.InheritanceTypes; }
}
public override ReadOnlyCollection<MetaType> DerivedTypes {
get {
// LOCKING: Cannot initialize at construction because derived types
// won't exist yet.
if (this.derivedTypes == null) {
lock (this.locktarget) {
if (this.derivedTypes == null) {
List<MetaType> dTypes = new List<MetaType>();
foreach (MetaType mt in this.InheritanceTypes) {
if (mt.Type.BaseType == this.type)
dTypes.Add(mt);
}
this.derivedTypes = dTypes.AsReadOnly();
}
}
}
return this.derivedTypes;
}
}
public override MetaType GetInheritanceType(Type inheritanceType) {
foreach (MetaType mt in this.InheritanceTypes)
if (mt.Type == inheritanceType)
return mt;
return null;
}
public override MetaType GetTypeForInheritanceCode(object key) {
if (this.InheritanceRoot.Discriminator.Type == typeof(string)) {
string skey = (string)key;
foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
if (string.Compare((string)mt.InheritanceCode, skey, StringComparison.OrdinalIgnoreCase) == 0)
return mt;
}
}
else {
foreach (MetaType mt in this.InheritanceRoot.InheritanceTypes) {
if (object.Equals(mt.InheritanceCode, key))
return mt;
}
}
return null;
}
public override ReadOnlyCollection<MetaDataMember> DataMembers {
get { return this.dataMembers; }
}
public override ReadOnlyCollection<MetaDataMember> PersistentDataMembers {
get { return this.persistentDataMembers; }
}
public override ReadOnlyCollection<MetaDataMember> IdentityMembers {
get { return this.identities; }
}
public override ReadOnlyCollection<MetaAssociation> Associations {
get {
// LOCKING: Associations are late-expanded so that cycles are broken.
if (this.associations == null) {
lock (this.locktarget) {
if (this.associations == null) {
this.associations = this.dataMembers.Where(m => m.IsAssociation).Select(m => m.Association).ToList().AsReadOnly();
}
}
}
return this.associations;
}
}
public override MetaDataMember GetDataMember(MemberInfo mi) {
if (mi == null)
throw Error.ArgumentNull("mi");
MetaDataMember mm;
if (this.dataMemberMap.TryGetValue(InheritanceRules.DistinguishedMemberName(mi), out mm)) {
return mm;
} else {
if (mi.DeclaringType.IsInterface) {
throw Error.MappingOfInterfacesMemberIsNotSupported(mi.DeclaringType.Name, mi.Name);
} else { //the member is not mapped in the base class
throw Error.UnmappedClassMember(mi.DeclaringType.Name, mi.Name);
}
}
}
public override MethodInfo OnLoadedMethod {
get {
this.InitMethods();
return this.onLoadedMethod;
}
}
public override MethodInfo OnValidateMethod {
get {
this.InitMethods();
return this.onValidateMethod;
}
}
public override bool HasAnyValidateMethod {
get {
this.InitMethods();
return this.hasAnyValidateMethod;
}
}
public override bool HasAnyLoadMethod {
get {
this.InitMethods();
return this.hasAnyLoadMethod;
}
}
public override string ToString() {
return this.Name;
}
}
internal sealed class MappedDataMember : MetaDataMember {
MetaType declaringType;
MemberInfo member;
MemberInfo storageMember;
int ordinal;
Type type;
bool hasAccessors;
MetaAccessor accPublic;
MetaAccessor accPrivate;
MetaAccessor accDefValue;
MetaAccessor accDefSource;
MemberMapping memberMap;
MappedAssociation assoc;
bool isNullableType;
bool isDeferred;
bool isPrimaryKey;
bool isVersion;
bool isDBGenerated;
bool isDiscriminator;
bool canBeNull = true;
string dbType;
string expression;
string mappedName;
UpdateCheck updateCheck = UpdateCheck.Never;
AutoSync autoSync = AutoSync.Never;
object locktarget = new object(); // Hold locks on private object rather than public MetaType.
bool hasLoadMethod;
MethodInfo loadMethod;
internal MappedDataMember(MetaType declaringType, MemberInfo mi, MemberMapping map, int ordinal) {
this.declaringType = declaringType;
this.member = mi;
this.ordinal = ordinal;
this.type = TypeSystem.GetMemberType(mi);
this.isNullableType = TypeSystem.IsNullableType(this.type);
this.memberMap = map;
if (this.memberMap != null && this.memberMap.StorageMemberName != null) {
MemberInfo[] mis = mi.DeclaringType.GetMember(this.memberMap.StorageMemberName, BindingFlags.Instance | BindingFlags.NonPublic);
if (mis == null || mis.Length != 1) {
throw Error.BadStorageProperty(this.memberMap.StorageMemberName, mi.DeclaringType, mi.Name);
}
this.storageMember = mis[0];
}
Type storageType = this.storageMember != null ? TypeSystem.GetMemberType(this.storageMember) : this.type;
this.isDeferred = IsDeferredType(storageType);
ColumnMapping cmap = map as ColumnMapping;
if (cmap != null && cmap.IsDbGenerated && cmap.IsPrimaryKey) {
// auto-gen identities must be synced on insert
if ((cmap.AutoSync != AutoSync.Default) && (cmap.AutoSync != AutoSync.OnInsert)) {
throw Error.IncorrectAutoSyncSpecification(mi.Name);
}
}
if (cmap != null) {
this.isPrimaryKey = cmap.IsPrimaryKey;
this.isVersion = cmap.IsVersion;
this.isDBGenerated = cmap.IsDbGenerated || !string.IsNullOrEmpty(cmap.Expression) || this.isVersion;
this.isDiscriminator = cmap.IsDiscriminator;
this.canBeNull = cmap.CanBeNull == null ? this.isNullableType || !this.type.IsValueType : (bool)cmap.CanBeNull;
this.dbType = cmap.DbType;
this.expression = cmap.Expression;
this.updateCheck = cmap.UpdateCheck;
// auto-gen keys are always and only synced on insert
if (this.IsDbGenerated && this.IsPrimaryKey) {
this.autoSync = AutoSync.OnInsert;
}
else if (cmap.AutoSync != AutoSync.Default) {
// if the user has explicitly set it, use their value