/
EntityEntry.cs
4126 lines (3656 loc) · 195 KB
/
EntityEntry.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 (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
namespace System.Data.Entity.Core.Objects
{
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Common.Utils;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Data.Entity.Core.Objects.Internal;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
internal sealed class EntityEntry : ObjectStateEntry
{
private StateManagerTypeMetadata _cacheTypeMetadata;
private EntityKey _entityKey; // !null if IsKeyEntry or Entity
private IEntityWrapper _wrappedEntity; // Contains null entity if IsKeyEntry
// entity entry change tracking
private BitArray _modifiedFields; // only and always exists if state is Modified or after Delete() on Modified
private List<StateManagerValue> _originalValues; // only exists if _modifiedFields has a true-bit
// The _originalComplexObjects should always contain references to the values of complex objects which are "original"
// at the moment of calling GetComplexObjectSnapshot(). They are used to get original scalar values from _originalValues
// and to check if complex object instance was changed.
private Dictionary<object, Dictionary<int, object>> _originalComplexObjects; // used for POCO Complex Objects change tracking
private bool _requiresComplexChangeTracking;
private bool _requiresScalarChangeTracking;
private bool _requiresAnyChangeTracking;
#region RelationshipEnd fields
// <summary>
// Singlely-linked list of RelationshipEntry.
// One of the ends in the RelationshipEntry must equal this.EntityKey
// </summary>
private RelationshipEntry _headRelationshipEnds;
// <summary>
// Number of RelationshipEntry in the _relationshipEnds list.
// </summary>
private int _countRelationshipEnds;
#endregion
#region Constructors
// <summary>
// For testing purposes only.
// </summary>
internal EntityEntry()
: base(new ObjectStateManager(), null, EntityState.Unchanged)
{
}
// <summary>
// For testing purposes only.
// </summary>
internal EntityEntry(ObjectStateManager stateManager)
: base(stateManager, null, EntityState.Unchanged)
{
}
internal EntityEntry(
IEntityWrapper wrappedEntity, EntityKey entityKey, EntitySet entitySet, ObjectStateManager cache,
StateManagerTypeMetadata typeMetadata, EntityState state)
: base(cache, entitySet, state)
{
DebugCheck.NotNull(wrappedEntity);
DebugCheck.NotNull(wrappedEntity.Entity);
DebugCheck.NotNull(typeMetadata);
DebugCheck.NotNull(entitySet);
Debug.Assert((entityKey == null) || (entityKey.EntitySetName == entitySet.Name), "different entitySet");
_wrappedEntity = wrappedEntity;
_cacheTypeMetadata = typeMetadata;
_entityKey = entityKey;
wrappedEntity.ObjectStateEntry = this;
SetChangeTrackingFlags();
}
// <summary>
// Looks at the type of entity represented by this entry and sets flags defining the type of
// change tracking that will be needed. The three main types are:
// - Pure POCO objects or non-change-tracking proxies which need DetectChanges for everything.
// - Entities derived from EntityObject which don't need DetectChanges at all.
// - Change tracking proxies, which only need DetectChanges for complex properties.
// </summary>
private void SetChangeTrackingFlags()
{
_requiresScalarChangeTracking = Entity != null && !(Entity is IEntityWithChangeTracker);
_requiresComplexChangeTracking = Entity != null &&
(_requiresScalarChangeTracking ||
(WrappedEntity.IdentityType != Entity.GetType() &&
_cacheTypeMetadata.Members.Any(m => m.IsComplex)));
_requiresAnyChangeTracking = Entity != null &&
(!(Entity is IEntityWithRelationships) ||
_requiresComplexChangeTracking ||
_requiresScalarChangeTracking);
}
internal EntityEntry(EntityKey entityKey, EntitySet entitySet, ObjectStateManager cache, StateManagerTypeMetadata typeMetadata)
: base(cache, entitySet, EntityState.Unchanged)
{
DebugCheck.NotNull(entityKey);
DebugCheck.NotNull(entitySet);
DebugCheck.NotNull(typeMetadata);
Debug.Assert(entityKey.EntitySetName == entitySet.Name, "different entitySet");
_wrappedEntity = NullEntityWrapper.NullWrapper;
_entityKey = entityKey;
_cacheTypeMetadata = typeMetadata;
SetChangeTrackingFlags();
}
#endregion
#region Public members
public override bool IsRelationship
{
get
{
ValidateState();
return false;
}
}
public override object Entity
{
get
{
ValidateState();
return _wrappedEntity.Entity;
}
}
// <summary>
// The EntityKey associated with the ObjectStateEntry
// </summary>
public override EntityKey EntityKey
{
get
{
ValidateState();
return _entityKey;
}
internal set { _entityKey = value; }
}
internal IEnumerable<Tuple<AssociationSet, ReferentialConstraint>> ForeignKeyDependents
{
get
{
foreach (var foreignKey in ((EntitySet)EntitySet).ForeignKeyDependents)
{
var constraint = foreignKey.Item2;
var dependentType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)constraint.ToRole);
if (dependentType.IsAssignableFrom(_cacheTypeMetadata.DataRecordInfo.RecordType.EdmType))
{
yield return foreignKey;
}
}
}
}
internal IEnumerable<Tuple<AssociationSet, ReferentialConstraint>> ForeignKeyPrincipals
{
get
{
foreach (var foreignKey in ((EntitySet)EntitySet).ForeignKeyPrincipals)
{
var constraint = foreignKey.Item2;
var dependentType = MetadataHelper.GetEntityTypeForEnd((AssociationEndMember)constraint.FromRole);
if (dependentType.IsAssignableFrom(_cacheTypeMetadata.DataRecordInfo.RecordType.EdmType))
{
yield return foreignKey;
}
}
}
}
public override IEnumerable<string> GetModifiedProperties()
{
ValidateState();
if (EntityState.Modified == State
&& _modifiedFields != null)
{
Debug.Assert(null != _modifiedFields, "null fields");
for (var i = 0; i < _modifiedFields.Length; i++)
{
if (_modifiedFields[i])
{
yield return (GetCLayerName(i, _cacheTypeMetadata));
}
}
}
}
// <summary>
// Marks specified property as modified.
// </summary>
// <param name="propertyName"> This API recognizes the names in terms of OSpace </param>
// <exception cref="InvalidOperationException">If State is not Modified or Unchanged</exception>
public override void SetModifiedProperty(string propertyName)
{
// We need this because the Code Contract gets compiled out in the release build even though
// this method is effectively on the public surface because it overrides the abstract method on ObjectStateEntry.
// Using a CodeContractsFor class doesn't work in this case.
Check.NotEmpty(propertyName, "propertyName");
var ordinal = ValidateAndGetOrdinalForProperty(propertyName, "SetModifiedProperty");
Debug.Assert(
State == EntityState.Unchanged || State == EntityState.Modified, "ValidateAndGetOrdinalForProperty should have thrown.");
if (EntityState.Unchanged == State)
{
State = EntityState.Modified;
_cache.ChangeState(this, EntityState.Unchanged, State);
}
SetModifiedPropertyInternal(ordinal);
}
internal void SetModifiedPropertyInternal(int ordinal)
{
if (null == _modifiedFields)
{
_modifiedFields = new BitArray(GetFieldCount(_cacheTypeMetadata));
}
_modifiedFields[ordinal] = true;
}
private int ValidateAndGetOrdinalForProperty(string propertyName, string methodName)
{
DebugCheck.NotNull(propertyName);
// Throw for detached entities
ValidateState();
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotModifyKeyEntryState);
}
var ordinal = _cacheTypeMetadata.GetOrdinalforOLayerMemberName(propertyName);
if (ordinal == -1)
{
throw new ArgumentException(Strings.ObjectStateEntry_SetModifiedOnInvalidProperty(propertyName));
}
if (State == EntityState.Added
|| State == EntityState.Deleted)
{
// Threw for detached above; this throws for Added or Deleted entities
throw new InvalidOperationException(Strings.ObjectStateEntry_SetModifiedStates(methodName));
}
return ordinal;
}
// <summary>
// Rejects any changes made to the property with the given name since the property was last loaded,
// attached, saved, or changes were accepted. The orginal value of the property is stored and the
// property will no longer be marked as modified.
// </summary>
// <remarks>
// If the result is that no properties of the entity are marked as modified, then the entity will
// be marked as Unchanged.
// Changes to properties can only rejected for entities that are in the Modified or Unchanged state.
// Calling this method for entities in other states (Added, Deleted, or Detached) will result in
// an exception being thrown.
// Rejecting changes to properties of an Unchanged entity or unchanged properties of a Modifed
// is a no-op.
// </remarks>
// <param name="propertyName"> The name of the property to change. </param>
public override void RejectPropertyChanges(string propertyName)
{
// We need this because the Code Contract gets compiled out in the release build even though
// this method is effectively on the public surface because it overrides the abstract method on ObjectStateEntry.
// Using a CodeContractsFor class doesn't work in this case.
Check.NotEmpty(propertyName, "propertyName");
var ordinal = ValidateAndGetOrdinalForProperty(propertyName, "RejectPropertyChanges");
if (State == EntityState.Unchanged)
{
// No-op for unchanged entities since all properties must be unchanged.
return;
}
Debug.Assert(State == EntityState.Modified, "Should have handled all other states above.");
if (_modifiedFields != null
&& _modifiedFields[ordinal])
{
// Reject the change by setting the current value to the original value
DetectChangesInComplexProperties();
var originalValue = GetOriginalEntityValue(
_cacheTypeMetadata, ordinal, _wrappedEntity.Entity, ObjectStateValueRecord.OriginalReadonly);
SetCurrentEntityValue(_cacheTypeMetadata, ordinal, _wrappedEntity.Entity, originalValue);
_modifiedFields[ordinal] = false;
// Check if any properties remain modified. If any are modified, then we leave the entity state as Modified and we are done.
for (var i = 0; i < _modifiedFields.Length; i++)
{
if (_modifiedFields[i])
{
return;
}
}
// No properties are modified so change the state of the entity to Unchanged.
ChangeObjectState(EntityState.Unchanged);
}
}
// <summary>
// Original values
// </summary>
// <returns> DbDataRecord </returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public override DbDataRecord OriginalValues
{
get { return InternalGetOriginalValues(true /*readOnly*/); }
}
// <summary>
// Gets a version of the OriginalValues property that can be updated
// </summary>
public override OriginalValueRecord GetUpdatableOriginalValues()
{
return (OriginalValueRecord)InternalGetOriginalValues(false /*readOnly*/);
}
private DbDataRecord InternalGetOriginalValues(bool readOnly)
{
ValidateState();
if (State == EntityState.Added)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_OriginalValuesDoesNotExist);
}
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
}
else
{
DetectChangesInComplexProperties();
if (readOnly)
{
return new ObjectStateEntryDbDataRecord(this, _cacheTypeMetadata, _wrappedEntity.Entity);
}
else
{
return new ObjectStateEntryOriginalDbUpdatableDataRecord_Public(
this, _cacheTypeMetadata, _wrappedEntity.Entity, s_EntityRoot);
}
}
}
private void DetectChangesInComplexProperties()
{
if (RequiresScalarChangeTracking)
{
// POCO: the snapshot of complex objects has to be updated
// without chaning state of the entry or marking properties as modified.
// The IsOriginalValuesGetter is used in EntityMemberChanged to skip the state transition.
// The snapshot has to be updated in case the complex object instance was changed (not only scalar values).
ObjectStateManager.TransactionManager.BeginOriginalValuesGetter();
try
{
// Process only complex objects. The method will not change the state of the entry.
DetectChangesInProperties(true /*detectOnlyComplexProperties*/);
}
finally
{
ObjectStateManager.TransactionManager.EndOriginalValuesGetter();
}
}
}
// <summary>
// Current values
// </summary>
// <returns> DbUpdatableDataRecord </returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public override CurrentValueRecord CurrentValues
{
get
{
ValidateState();
if (State == EntityState.Deleted)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CurrentValuesDoesNotExist);
}
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
}
else
{
return new ObjectStateEntryDbUpdatableDataRecord(this, _cacheTypeMetadata, _wrappedEntity.Entity);
}
}
}
public override void Delete()
{
// doFixup flag is used for Cache and Collection & Ref consistency
// When some entity is deleted if "doFixup" is true then Delete method
// calls the Collection & Ref code to do the necessary fix-ups.
// "doFixup" equals to False is only called from EntityCollection & Ref code
Delete( /*doFixup*/true);
}
// <summary>
// API to accept the current values as original values and mark the entity as Unchanged.
// </summary>
public override void AcceptChanges()
{
ValidateState();
if (ObjectStateManager.EntryHasConceptualNull(this))
{
throw new InvalidOperationException(Strings.ObjectContext_CommitWithConceptualNull);
}
Debug.Assert(!IsKeyEntry || State == EntityState.Unchanged, "Key ObjectStateEntries must always be unchanged.");
switch (State)
{
case EntityState.Deleted:
CascadeAcceptChanges();
// Current entry could be already detached if this is relationship entry and if one end of relationship was a KeyEntry
if (_cache != null)
{
_cache.ChangeState(this, EntityState.Deleted, EntityState.Detached);
}
break;
case EntityState.Added:
// If this entry represents an entity, perform key fixup.
Debug.Assert(Entity != null, "Non-relationship entries should have a non-null entity.");
Debug.Assert((object)_entityKey != null, "All entities in the state manager should have a non-null EntityKey.");
Debug.Assert(_entityKey.IsTemporary, "All entities in the Added state should have a temporary EntityKey.");
// Retrieve referential constraint properties from Principal entities (possibly recursively)
// and check referential constraint properties in the Dependent entities (1 level only)
// We have to do this before fixing up keys to preserve v1 behavior around when stubs are promoted.
// However, we can't check FKs until after fixup, which happens after key fixup. Therefore,
// we keep track of whether or not we need to go check again after fixup. Also, checking for independent associations
// happens using RelationshipEntries, while checking for constraints in FKs has to use the graph.
var skippedFKs = RetrieveAndCheckReferentialConstraintValuesInAcceptChanges();
_cache.FixupKey(this);
_modifiedFields = null;
_originalValues = null;
_originalComplexObjects = null;
State = EntityState.Unchanged;
if (skippedFKs)
{
// If we skipped checking constraints on any FK relationships above, then
// do it now on the fixuped RelatedEnds.
RelationshipManager.CheckReferentialConstraintProperties(this);
}
_wrappedEntity.TakeSnapshot(this);
break;
case EntityState.Modified:
_cache.ChangeState(this, EntityState.Modified, EntityState.Unchanged);
_modifiedFields = null;
_originalValues = null;
_originalComplexObjects = null;
State = EntityState.Unchanged;
_cache.FixupReferencesByForeignKeys(this);
// Need to check constraints here because fixup could have got us into an invalid state
RelationshipManager.CheckReferentialConstraintProperties(this);
_wrappedEntity.TakeSnapshot(this);
break;
case EntityState.Unchanged:
break;
}
}
public override void SetModified()
{
ValidateState();
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotModifyKeyEntryState);
}
else
{
if (EntityState.Unchanged == State)
{
State = EntityState.Modified;
_cache.ChangeState(this, EntityState.Unchanged, State);
}
else if (EntityState.Modified != State)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_SetModifiedStates("SetModified"));
}
}
}
public override RelationshipManager RelationshipManager
{
get
{
ValidateState();
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_RelationshipAndKeyEntriesDoNotHaveRelationshipManagers);
}
if (WrappedEntity.Entity == null)
{
throw new InvalidOperationException(Strings.ObjectStateManager_CannotGetRelationshipManagerForDetachedPocoEntity);
}
return WrappedEntity.RelationshipManager;
}
}
internal override BitArray ModifiedProperties
{
get { return _modifiedFields; }
}
// <summary>
// Changes state of the entry to the specified <paramref name="state" />
// </summary>
// <param name="state"> The requested state </param>
public override void ChangeState(EntityState state)
{
EntityUtil.CheckValidStateForChangeEntityState(state);
if (State == EntityState.Detached
&& state == EntityState.Detached)
{
return;
}
ValidateState();
// store a referece to the cache because this.ObjectStatemanager will be null if the requested state is Detached
var osm = ObjectStateManager;
osm.TransactionManager.BeginLocalPublicAPI();
try
{
ChangeObjectState(state);
}
finally
{
osm.TransactionManager.EndLocalPublicAPI();
}
}
// <summary>
// Apply modified properties to the original object.
// </summary>
// <param name="currentEntity"> object with modified properties </param>
public override void ApplyCurrentValues(object currentEntity)
{
Check.NotNull(currentEntity, "currentEntity");
ValidateState();
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
}
var wrappedEntity = ObjectStateManager.EntityWrapperFactory.WrapEntityUsingStateManager(currentEntity, ObjectStateManager);
ApplyCurrentValuesInternal(wrappedEntity);
}
// <summary>
// Apply original values to the entity.
// </summary>
// <param name="originalEntity"> The object with original values </param>
public override void ApplyOriginalValues(object originalEntity)
{
Check.NotNull(originalEntity, "originalEntity");
ValidateState();
if (IsKeyEntry)
{
throw new InvalidOperationException(Strings.ObjectStateEntry_CannotAccessKeyEntryValues);
}
var wrappedEntity = ObjectStateManager.EntityWrapperFactory.WrapEntityUsingStateManager(originalEntity, ObjectStateManager);
ApplyOriginalValuesInternal(wrappedEntity);
}
#endregion // Public members
#region RelationshipEnd methods
// <summary>
// Add a RelationshipEntry (one of its ends must equal this.EntityKey)
// </summary>
internal void AddRelationshipEnd(RelationshipEntry item)
{
DebugCheck.NotNull(item);
DebugCheck.NotNull(item.RelationshipWrapper);
Debug.Assert(0 <= _countRelationshipEnds, "negative _relationshipEndCount");
Debug.Assert(
EntityKey.Equals(item.RelationshipWrapper.Key0) || EntityKey.Equals(item.RelationshipWrapper.Key1),
"entity key doesn't match");
#if DEBUG
for (var current = _headRelationshipEnds;
null != current;
current = current.GetNextRelationshipEnd(EntityKey))
{
Debug.Assert(!ReferenceEquals(item, current), "RelationshipEntry already in list");
Debug.Assert(!item.RelationshipWrapper.Equals(current.RelationshipWrapper), "RelationshipWrapper already in list");
}
#endif
// the item will become the head of the list
// i.e. you walk the list in reverse order of items being added
item.SetNextRelationshipEnd(EntityKey, _headRelationshipEnds);
_headRelationshipEnds = item;
_countRelationshipEnds++;
Debug.Assert(_countRelationshipEnds == (new RelationshipEndEnumerable(this)).ToArray().Length, "different count");
}
// <summary>
// Determines if a given relationship entry is present in the list of entries
// </summary>
// <param name="item"> The entry to look for </param>
// <returns> True of the relationship end is found </returns>
internal bool ContainsRelationshipEnd(RelationshipEntry item)
{
for (var current = _headRelationshipEnds;
null != current;
current = current.GetNextRelationshipEnd(EntityKey))
{
if (ReferenceEquals(current, item))
{
return true;
}
}
return false;
}
// <summary>
// Remove a RelationshipEntry (one of its ends must equal this.EntityKey)
// </summary>
internal void RemoveRelationshipEnd(RelationshipEntry item)
{
DebugCheck.NotNull(item);
DebugCheck.NotNull(item.RelationshipWrapper);
Debug.Assert(1 <= _countRelationshipEnds, "negative _relationshipEndCount");
Debug.Assert(
EntityKey.Equals(item.RelationshipWrapper.Key0) || EntityKey.Equals(item.RelationshipWrapper.Key1),
"entity key doesn't match");
// walk the singly-linked list, remembering the previous node so we can remove the current node
var current = _headRelationshipEnds;
RelationshipEntry previous = null;
var previousIsKey0 = false;
while (null != current)
{
// short-circuit if the key matches either candidate by reference
var currentIsKey0 = ReferenceEquals(EntityKey, current.Key0) ||
(!ReferenceEquals(EntityKey, current.Key1) && EntityKey.Equals(current.Key0));
if (ReferenceEquals(item, current))
{
RelationshipEntry next;
if (currentIsKey0)
{
// if this.EntityKey matches Key0, NextKey0 is the next element in the lsit
Debug.Assert(EntityKey.Equals(current.RelationshipWrapper.Key0), "entity key didn't match");
next = current.NextKey0;
current.NextKey0 = null;
}
else
{
// if this.EntityKey matches Key1, NextKey1 is the next element in the lsit
Debug.Assert(EntityKey.Equals(current.RelationshipWrapper.Key1), "entity key didn't match");
next = current.NextKey1;
current.NextKey1 = null;
}
if (null == previous)
{
_headRelationshipEnds = next;
}
else if (previousIsKey0)
{
previous.NextKey0 = next;
}
else
{
previous.NextKey1 = next;
}
--_countRelationshipEnds;
Debug.Assert(_countRelationshipEnds == (new RelationshipEndEnumerable(this)).ToArray().Length, "different count");
return;
}
Debug.Assert(
!item.RelationshipWrapper.Equals(current.RelationshipWrapper), "same wrapper, different RelationshipEntry instances");
previous = current;
current = currentIsKey0 ? current.NextKey0 : current.NextKey1;
previousIsKey0 = currentIsKey0;
}
Debug.Assert(false, "didn't remove a RelationshipEntry");
}
// <summary>
// Update one of the ends for the related RelationshipEntry
// </summary>
// <param name="oldKey"> the EntityKey the relationship should currently have </param>
// <param name="promotedEntry"> if promoting entity stub to full entity </param>
internal void UpdateRelationshipEnds(EntityKey oldKey, EntityEntry promotedEntry)
{
DebugCheck.NotNull(oldKey);
Debug.Assert(!ReferenceEquals(this, promotedEntry), "shouldn't be same reference");
// traverse the list to update one of the ends in the relationship entry
var count = 0;
var next = _headRelationshipEnds;
while (null != next)
{
// get the next relationship end before we change the key of current relationship end
var current = next;
next = next.GetNextRelationshipEnd(oldKey);
// update the RelationshipEntry from the temporary key to real key
current.ChangeRelatedEnd(oldKey, EntityKey);
// If we have a promoted entry, copy the relationship entries to the promoted entry
// only if the promoted entry doesn't already know about that particular relationship entry
// This can be the case with self referencing entities
if (null != promotedEntry
&& !promotedEntry.ContainsRelationshipEnd(current))
{
// all relationship ends moved to new promotedEntry
promotedEntry.AddRelationshipEnd(current);
}
++count;
}
Debug.Assert(count == _countRelationshipEnds, "didn't traverse all relationships");
if (null != promotedEntry)
{
// cleanup existing (dead) entry to reduce confusion
_headRelationshipEnds = null;
_countRelationshipEnds = 0;
}
}
#region Enumerable and Enumerator
internal RelationshipEndEnumerable GetRelationshipEnds()
{
return new RelationshipEndEnumerable(this);
}
// <summary>
// An enumerable so that EntityEntry doesn't implement it
// </summary>
internal struct RelationshipEndEnumerable : IEnumerable<RelationshipEntry>, IEnumerable<IEntityStateEntry>
{
internal static readonly RelationshipEntry[] EmptyRelationshipEntryArray = new RelationshipEntry[0];
private readonly EntityEntry _entityEntry;
internal RelationshipEndEnumerable(EntityEntry entityEntry)
{
// its okay if entityEntry is null
_entityEntry = entityEntry;
}
public RelationshipEndEnumerator GetEnumerator()
{
return new RelationshipEndEnumerator(_entityEntry);
}
IEnumerator<IEntityStateEntry> IEnumerable<IEntityStateEntry>.GetEnumerator()
{
return GetEnumerator();
}
IEnumerator<RelationshipEntry> IEnumerable<RelationshipEntry>.GetEnumerator()
{
Debug.Assert(false, "dead code, don't box the RelationshipEndEnumerable");
return GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
Debug.Assert(false, "dead code, don't box the RelationshipEndEnumerable");
return GetEnumerator();
}
// <summary>
// Convert the singly-linked list into an Array
// </summary>
internal RelationshipEntry[] ToArray()
{
RelationshipEntry[] list = null;
if ((null != _entityEntry)
&& (0 < _entityEntry._countRelationshipEnds))
{
var relationshipEnd = _entityEntry._headRelationshipEnds;
list = new RelationshipEntry[_entityEntry._countRelationshipEnds];
for (var i = 0; i < list.Length; ++i)
{
Debug.Assert(null != relationshipEnd, "count larger than list");
Debug.Assert(
_entityEntry.EntityKey.Equals(relationshipEnd.Key0) || _entityEntry.EntityKey.Equals(relationshipEnd.Key1),
"entity key mismatch");
list[i] = relationshipEnd;
relationshipEnd = relationshipEnd.GetNextRelationshipEnd(_entityEntry.EntityKey);
}
Debug.Assert(null == relationshipEnd, "count smaller than list");
}
return list ?? EmptyRelationshipEntryArray;
}
}
// <summary>
// An enumerator to walk the RelationshipEntry linked-list
// </summary>
internal struct RelationshipEndEnumerator : IEnumerator<RelationshipEntry>, IEnumerator<IEntityStateEntry>
{
private readonly EntityEntry _entityEntry;
private RelationshipEntry _current;
internal RelationshipEndEnumerator(EntityEntry entityEntry)
{
_entityEntry = entityEntry;
_current = null;
}
public RelationshipEntry Current
{
get { return _current; }
}
IEntityStateEntry IEnumerator<IEntityStateEntry>.Current
{
get { return _current; }
}
object IEnumerator.Current
{
get
{
Debug.Assert(false, "dead code, don't box the RelationshipEndEnumerator");
return _current;
}
}
public void Dispose()
{
}
public bool MoveNext()
{
if (null != _entityEntry)
{
if (null == _current)
{
_current = _entityEntry._headRelationshipEnds;
}
else
{
_current = _current.GetNextRelationshipEnd(_entityEntry.EntityKey);
}
}
return (null != _current);
}
public void Reset()
{
Debug.Assert(false, "not implemented");
}
}
#endregion
#endregion
#region ObjectStateEntry members
internal override bool IsKeyEntry
{
get { return null == _wrappedEntity.Entity; }
}
// <summary>
// Reuse or create a new (Entity)DataRecordInfo.
// </summary>
internal override DataRecordInfo GetDataRecordInfo(StateManagerTypeMetadata metadata, object userObject)
{
if (Helper.IsEntityType(metadata.CdmMetadata.EdmType)
&& (null != (object)_entityKey))
{
// is EntityType with null EntityKey when constructing new EntityKey during ObjectStateManager.Add
// always need a new EntityRecordInfo instance for the different key (reusing DataRecordInfo's FieldMetadata).
return new EntityRecordInfo(metadata.DataRecordInfo, _entityKey, (EntitySet)EntitySet);
}
else
{
// ObjectContext.AttachTo uses CurrentValueRecord to build EntityKey for EntityType
// so the Entity doesn't have an EntityKey yet
return metadata.DataRecordInfo;
}
}
internal override void Reset()
{
Debug.Assert(_cache != null, "Cannot Reset an entity that is not currently attached to a context.");
RemoveFromForeignKeyIndex();
_cache.ForgetEntryWithConceptualNull(this, resetAllKeys: true);
DetachObjectStateManagerFromEntity();
_wrappedEntity = NullEntityWrapper.NullWrapper;
_entityKey = null;
_modifiedFields = null;
_originalValues = null;
_originalComplexObjects = null;
SetChangeTrackingFlags();
base.Reset();
}
internal override Type GetFieldType(int ordinal, StateManagerTypeMetadata metadata)
{
// 'metadata' is used for ComplexTypes
return metadata.GetFieldType(ordinal);
}
internal override string GetCLayerName(int ordinal, StateManagerTypeMetadata metadata)
{
return metadata.CLayerMemberName(ordinal);
}
internal override int GetOrdinalforCLayerName(string name, StateManagerTypeMetadata metadata)
{
return metadata.GetOrdinalforCLayerMemberName(name);
}
internal override void RevertDelete()
{
// just change the state from deleted, to last state.
State = (_modifiedFields == null) ? EntityState.Unchanged : EntityState.Modified;
_cache.ChangeState(this, EntityState.Deleted, State);
}
internal override int GetFieldCount(StateManagerTypeMetadata metadata)
{
return metadata.FieldCount;
}
private void CascadeAcceptChanges()
{
foreach (var entry in _cache.CopyOfRelationshipsByKey(EntityKey))
{
// CascadeAcceptChanges is only called on Entity ObjectStateEntry when it is
// in deleted state. Entity is in deleted state therefore for all related Relationship
// cache entries only valid state is Deleted.
Debug.Assert(entry.State == EntityState.Deleted, "Relationship ObjectStateEntry should be in deleted state");
entry.AcceptChanges();
}