This repository has been archived by the owner on Nov 29, 2017. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 54
/
ObjectContext.cs
4822 lines (4267 loc) · 249 KB
/
ObjectContext.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.Configuration;
using System.Data.Common;
using System.Data.Entity.Config;
using System.Data.Entity.Core.Common;
using System.Data.Entity.Core.Common.CommandTrees;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Data.Entity.Core.Common.Internal.Materialization;
using System.Data.Entity.Core.Common.Utils;
using System.Data.Entity.Core.EntityClient;
using System.Data.Entity.Core.EntityClient.Internal;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Core.Objects.DataClasses;
using System.Data.Entity.Core.Objects.ELinq;
using System.Data.Entity.Core.Objects.Internal;
using System.Data.Entity.Core.Query.InternalTrees;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Internal;
using System.Data.Entity.Resources;
using System.Data.Entity.Utilities;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.Versioning;
using System.Text;
#if !NET40
using System.Threading;
using System.Threading.Tasks;
#endif
using System.Transactions;
/// <summary>
/// ObjectContext is the top-level object that encapsulates a connection between the CLR and the database,
/// serving as a gateway for Create, Read, Update, and Delete operations.
/// </summary>
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public class ObjectContext : IDisposable, IObjectContextAdapter
{
#region Fields
private bool _disposed;
private readonly IEntityAdapter _adapter;
// Connection may be null if used by ObjectMaterializer for detached ObjectContext,
// but those code paths should not touch the connection.
//
// If the connection is null, this indicates that this object has been disposed.
// Disposal for this class doesn't mean complete disposal,
// but rather the disposal of the underlying connection object if the ObjectContext owns the connection,
// or the separation of the underlying connection object from the ObjectContext if the ObjectContext does not own the connection.
//
// Operations that require a connection should throw an ObjectDiposedException if the connection is null.
// Other operations that do not need a connection should continue to work after disposal.
private EntityConnection _connection;
private readonly MetadataWorkspace _workspace;
private ObjectStateManager _objectStateManager;
private ClrPerspective _perspective;
private readonly bool _createdConnection;
private bool _openedConnection; // whether or not the context opened the connection to do an operation
private int _connectionRequestCount; // the number of active requests for an open connection
private int? _queryTimeout;
private Transaction _lastTransaction;
private readonly bool _disallowSettingDefaultContainerName;
private EventHandler _onSavingChanges;
private ObjectMaterializedEventHandler _onObjectMaterialized;
private ObjectQueryProvider _queryProvider;
private readonly EntityWrapperFactory _entityWrapperFactory;
private readonly ObjectQueryExecutionPlanFactory _objectQueryExecutionPlanFactory;
private readonly Translator _translator;
private readonly ColumnMapFactory _columnMapFactory;
private readonly ObjectContextOptions _options = new ObjectContextOptions();
private const string UseLegacyPreserveChangesBehavior = "EntityFramework_UseLegacyPreserveChangesBehavior";
private readonly ThrowingMonitor _asyncMonitor = new ThrowingMonitor();
private DbInterceptionContext _interceptionContext;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" /> class with the given connection. During construction, the metadata workspace is extracted from the
/// <see
/// cref="T:System.Data.Entity.Core.EntityClient.EntityConnection" />
/// object.
/// </summary>
/// <param name="connection">
/// An <see cref="T:System.Data.Entity.Core.EntityClient.EntityConnection" /> that contains references to the model and to the data source connection.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The connection is null.</exception>
/// <exception cref="T:System.ArgumentException">The connection is invalid or the metadata workspace is invalid. </exception>
public ObjectContext(EntityConnection connection)
: this(connection, true, null)
{
_createdConnection = false;
}
/// <summary>
/// Creates an ObjectContext with the given connection and metadata workspace.
/// </summary>
/// <param name="connection"> connection to the store </param>
/// <param name="contextOwnsConnection"> If set to true the connection is disposed when the context is disposed, otherwise the caller must dispose the connection. </param>
public ObjectContext(EntityConnection connection, bool contextOwnsConnection)
: this(connection, true, null)
{
_createdConnection = contextOwnsConnection;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" /> class with the given connection string and default entity container name.
/// </summary>
/// <param name="connectionString">The connection string, which also provides access to the metadata information.</param>
/// <exception cref="T:System.ArgumentNullException">The connectionString is null.</exception>
/// <exception cref="T:System.ArgumentException">The connectionString is invalid or the metadata workspace is not valid. </exception>
[ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource
[ResourceConsumption(ResourceScope.Machine)] //For CreateEntityConnection method. But the paths are not created in this method.
[SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope",
Justification = "Object is in fact passed to property of the class and gets Disposed properly in the Dispose() method.")]
public ObjectContext(string connectionString)
: this(CreateEntityConnection(connectionString), false, null)
{
_createdConnection = true;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" /> class with a given connection string and entity container name.
/// </summary>
/// <param name="connectionString">The connection string, which also provides access to the metadata information.</param>
/// <param name="defaultContainerName">The name of the default entity container. When the defaultContainerName is set through this method, the property becomes read-only.</param>
/// <exception cref="T:System.ArgumentNullException">The connectionString is null.</exception>
/// <exception cref="T:System.ArgumentException">The connectionString , defaultContainerName , or metadata workspace is not valid.</exception>
[ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource
[ResourceConsumption(ResourceScope.Machine)] //For ObjectContext method. But the paths are not created in this method.
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "Class is internal and methods are made virtual for testing purposes only. They cannot be overrided by user.")]
protected ObjectContext(string connectionString, string defaultContainerName)
: this(connectionString)
{
DefaultContainerName = defaultContainerName;
if (!string.IsNullOrEmpty(defaultContainerName))
{
_disallowSettingDefaultContainerName = true;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" /> class with a given connection and entity container name.
/// </summary>
/// <param name="connection">
/// An <see cref="T:System.Data.Entity.Core.EntityClient.EntityConnection" /> that contains references to the model and to the data source connection.
/// </param>
/// <param name="defaultContainerName">The name of the default entity container. When the defaultContainerName is set through this method, the property becomes read-only.</param>
/// <exception cref="T:System.ArgumentNullException">The connection is null.</exception>
/// <exception cref="T:System.ArgumentException">The connection , defaultContainerName , or metadata workspace is not valid.</exception>
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "Class is internal and methods are made virtual for testing purposes only. They cannot be overrided by user.")]
protected ObjectContext(EntityConnection connection, string defaultContainerName)
: this(connection)
{
DefaultContainerName = defaultContainerName;
if (!string.IsNullOrEmpty(defaultContainerName))
{
_disallowSettingDefaultContainerName = true;
}
}
[SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")]
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors",
Justification = "Class is internal and methods are made virtual for testing purposes only. They cannot be overrided by user.")]
internal ObjectContext(
EntityConnection connection,
bool isConnectionConstructor,
ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory,
Translator translator = null,
ColumnMapFactory columnMapFactory = null)
{
Check.NotNull(connection, "connection");
_interceptionContext = new DbInterceptionContext().WithObjectContext(this);
_objectQueryExecutionPlanFactory = objectQueryExecutionPlanFactory ?? new ObjectQueryExecutionPlanFactory();
_translator = translator ?? new Translator();
_columnMapFactory = columnMapFactory ?? new ColumnMapFactory();
_adapter = new EntityAdapter(this);
_connection = connection;
_connection.AssociateContext(this);
_connection.StateChange += ConnectionStateChange;
_entityWrapperFactory = new EntityWrapperFactory();
// Ensure a valid connection
var connectionString = connection.ConnectionString;
if (connectionString == null
|| connectionString.Trim().Length == 0)
{
throw isConnectionConstructor
? new ArgumentException(Strings.ObjectContext_InvalidConnection, "connection", null)
: new ArgumentException(Strings.ObjectContext_InvalidConnectionString, "connectionString", null);
}
try
{
_workspace = RetrieveMetadataWorkspaceFromConnection();
}
catch (InvalidOperationException e)
{
// Intercept exceptions retrieving workspace, and wrap exception in appropriate
// message based on which constructor pattern is being used.
throw isConnectionConstructor
? new ArgumentException(Strings.ObjectContext_InvalidConnection, "connection", e)
: new ArgumentException(Strings.ObjectContext_InvalidConnectionString, "connectionString", e);
}
Debug.Assert(_workspace != null);
// load config file properties
var value = ConfigurationManager.AppSettings[UseLegacyPreserveChangesBehavior];
var useV35Behavior = false;
if (Boolean.TryParse(value, out useV35Behavior))
{
ContextOptions.UseLegacyPreserveChangesBehavior = useV35Behavior;
}
}
/// <summary>
/// For testing porpoises only.
/// </summary>
internal ObjectContext(
ObjectQueryExecutionPlanFactory objectQueryExecutionPlanFactory = null,
Translator translator = null,
ColumnMapFactory columnMapFactory = null,
IEntityAdapter adapter = null)
{
_interceptionContext = new DbInterceptionContext().WithObjectContext(this);
_objectQueryExecutionPlanFactory = objectQueryExecutionPlanFactory ?? new ObjectQueryExecutionPlanFactory();
_translator = translator ?? new Translator();
_columnMapFactory = columnMapFactory ?? new ColumnMapFactory();
_adapter = adapter ?? new EntityAdapter(this);
}
#endregion //Constructors
#region Properties
/// <summary>Gets the connection used by the object context.</summary>
/// <returns>
/// A <see cref="T:System.Data.Common.DbConnection" /> object that is the connection.
/// </returns>
/// <exception cref="T:System.ObjectDisposedException">
/// When the <see cref="T:System.Data.Entity.Core.Objects.ObjectContext" /> instance has been disposed.
/// </exception>
public virtual DbConnection Connection
{
get
{
if (_connection == null)
{
throw new ObjectDisposedException(null, Strings.ObjectContext_ObjectDisposed);
}
return _connection;
}
}
/// <summary>Gets or sets the default container name.</summary>
/// <returns>
/// A <see cref="T:System.String" /> that is the default container name.
/// </returns>
public virtual string DefaultContainerName
{
get
{
var container = Perspective.GetDefaultContainer();
return ((null != container) ? container.Name : String.Empty);
}
set
{
if (!_disallowSettingDefaultContainerName)
{
Perspective.SetDefaultContainer(value);
}
else
{
throw new InvalidOperationException(Strings.ObjectContext_CannotSetDefaultContainerName);
}
}
}
/// <summary>Gets the metadata workspace used by the object context. </summary>
/// <returns>
/// The <see cref="T:System.Data.Entity.Core.Metadata.Edm.MetadataWorkspace" /> object associated with this
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </returns>
public virtual MetadataWorkspace MetadataWorkspace
{
get { return _workspace; }
}
/// <summary>Gets the object state manager used by the object context to track object changes.</summary>
/// <returns>
/// The <see cref="T:System.Data.Entity.Core.Objects.ObjectStateManager" /> used by this
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </returns>
public virtual ObjectStateManager ObjectStateManager
{
get
{
if (_objectStateManager == null)
{
_objectStateManager = new ObjectStateManager(_workspace);
}
return _objectStateManager;
}
}
/// <summary>
/// ClrPerspective based on the MetadataWorkspace.
/// </summary>
internal ClrPerspective Perspective
{
get
{
if (_perspective == null)
{
_perspective = new ClrPerspective(MetadataWorkspace);
}
return _perspective;
}
}
/// <summary>Gets or sets the timeout value, in seconds, for all object context operations. A null value indicates that the default value of the underlying provider will be used.</summary>
/// <returns>
/// An <see cref="T:System.Int32" /> value that is the timeout value, in seconds.
/// </returns>
/// <exception cref="T:System.ArgumentException">The timeout value is less than 0. </exception>
public virtual int? CommandTimeout
{
get { return _queryTimeout; }
set
{
if (value.HasValue
&& value < 0)
{
throw new ArgumentException(Strings.ObjectContext_InvalidCommandTimeout, "value");
}
_queryTimeout = value;
}
}
/// <summary>Gets the LINQ query provider associated with this object context.</summary>
/// <returns>
/// The <see cref="T:System.Linq.IQueryProvider" /> instance used by this object context.
/// </returns>
protected internal virtual IQueryProvider QueryProvider
{
get
{
if (null == _queryProvider)
{
_queryProvider = new ObjectQueryProvider(this);
}
return _queryProvider;
}
}
/// <summary>
/// Whether or not we are in the middle of materialization
/// Used to suppress operations such as lazy loading that are not allowed during materialization
/// </summary>
internal bool InMaterialization { get; set; }
/// <summary>
/// Indicates whether there is an asynchronous method currently running that uses this instance
/// </summary>
internal ThrowingMonitor AsyncMonitor
{
get { return _asyncMonitor; }
}
/// <summary>
/// Gets the <see cref="T:System.Data.Entity.Core.Objects.ObjectContextOptions" /> instance that contains options that affect the behavior of the
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </summary>
/// <returns>
/// The <see cref="T:System.Data.Entity.Core.Objects.ObjectContextOptions" /> instance that contains options that affect the behavior of the
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </returns>
public virtual ObjectContextOptions ContextOptions
{
get { return _options; }
}
internal CollectionColumnMap ColumnMapBuilder { get; set; }
internal virtual EntityWrapperFactory EntityWrapperFactory
{
get { return _entityWrapperFactory; }
}
/// <summary>
/// Returns itself. ObjectContext implements <see cref="IObjectContextAdapter" /> to provide a common
/// interface for <see cref="DbContext" /> and ObjectContext both of which will return the underlying
/// ObjectContext.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
ObjectContext IObjectContextAdapter.ObjectContext
{
get { return this; }
}
internal DbInterceptionContext InterceptionContext
{
get { return _interceptionContext; }
set
{
DebugCheck.NotNull(_interceptionContext);
Debug.Assert(_interceptionContext.ObjectContexts.Contains(this));
_interceptionContext = value;
}
}
#endregion //Properties
#region Events
/// <summary>Occurs when changes are saved to the data source. </summary>
public event EventHandler SavingChanges
{
add { _onSavingChanges += value; }
remove { _onSavingChanges -= value; }
}
/// <summary>
/// A private helper function for the _savingChanges/SavingChanges event.
/// </summary>
private void OnSavingChanges()
{
if (null != _onSavingChanges)
{
_onSavingChanges(this, new EventArgs());
}
}
/// <summary>Occurs when a new entity object is created from data in the data source as part of a query or load operation. </summary>
public event ObjectMaterializedEventHandler ObjectMaterialized
{
add { _onObjectMaterialized += value; }
remove { _onObjectMaterialized -= value; }
}
internal void OnObjectMaterialized(object entity)
{
if (null != _onObjectMaterialized)
{
_onObjectMaterialized(this, new ObjectMaterializedEventArgs(entity));
}
}
/// <summary>
/// Returns true if any handlers for the ObjectMaterialized event exist. This is
/// used for perf reasons to avoid collecting the information needed for the event
/// if there is no point in firing it.
/// </summary>
internal bool OnMaterializedHasHandlers
{
get { return _onObjectMaterialized != null && _onObjectMaterialized.GetInvocationList().Length != 0; }
}
#endregion //Events
#region Methods
/// <summary>Accepts all changes made to objects in the object context.</summary>
public virtual void AcceptAllChanges()
{
ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid();
if (ObjectStateManager.SomeEntryWithConceptualNullExists())
{
throw new InvalidOperationException(Strings.ObjectContext_CommitWithConceptualNull);
}
// There are scenarios in which order of calling AcceptChanges does matter:
// in case there is an entity in Deleted state and another entity in Added state with the same ID -
// it is necessary to call AcceptChanges on Deleted entity before calling AcceptChanges on Added entity
// (doing this in the other order there is conflict of keys).
foreach (var entry in ObjectStateManager.GetObjectStateEntries(EntityState.Deleted))
{
entry.AcceptChanges();
}
foreach (var entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
{
entry.AcceptChanges();
}
ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid();
}
private void VerifyRootForAdd(
bool doAttach, string entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, out EntitySet entitySet,
out bool isNoOperation)
{
isNoOperation = false;
EntitySet entitySetFromName = null;
if (doAttach)
{
// For AttachTo the entity set name is optional
if (!String.IsNullOrEmpty(entitySetName))
{
entitySetFromName = GetEntitySetFromName(entitySetName);
}
}
else
{
// For AddObject the entity set name is obligatory
entitySetFromName = GetEntitySetFromName(entitySetName);
}
// Find entity set using entity key
EntitySet entitySetFromKey = null;
var key = existingEntry != null ? existingEntry.EntityKey : wrappedEntity.GetEntityKeyFromEntity();
if (null != (object)key)
{
entitySetFromKey = key.GetEntitySet(MetadataWorkspace);
if (entitySetFromName != null)
{
// both entity sets are not null, compare them
EntityUtil.ValidateEntitySetInKey(key, entitySetFromName, "entitySetName");
}
key.ValidateEntityKey(_workspace, entitySetFromKey);
}
entitySet = entitySetFromKey ?? entitySetFromName;
// Check if entity set was found
if (entitySet == null)
{
throw new InvalidOperationException(Strings.ObjectContext_EntitySetNameOrEntityKeyRequired);
}
ValidateEntitySet(entitySet, wrappedEntity.IdentityType);
// If in the middle of Attach, try to find the entry by key
if (doAttach && existingEntry == null)
{
// If we don't already have a key, create one now
if (null == (object)key)
{
key = ObjectStateManager.CreateEntityKey(entitySet, wrappedEntity.Entity);
}
existingEntry = ObjectStateManager.FindEntityEntry(key);
}
if (null != existingEntry
&& !(doAttach && existingEntry.IsKeyEntry))
{
if (!ReferenceEquals(existingEntry.Entity, wrappedEntity.Entity))
{
throw new InvalidOperationException(Strings.ObjectStateManager_ObjectStateManagerContainsThisEntityKey);
}
else
{
var exptectedState = doAttach ? EntityState.Unchanged : EntityState.Added;
if (existingEntry.State != exptectedState)
{
throw doAttach
? new InvalidOperationException(Strings.ObjectContext_EntityAlreadyExistsInObjectStateManager)
: new InvalidOperationException(
Strings.ObjectStateManager_DoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(
existingEntry.State));
}
else
{
// AttachTo:
// Attach is no-op when the existing entry is not a KeyEntry
// and it's entity is the same entity instance and it's state is Unchanged
// AddObject:
// AddObject is no-op when the existing entry's entity is the same entity
// instance and it's state is Added
isNoOperation = true;
return;
}
}
}
}
/// <summary>Adds an object to the object context. </summary>
/// <param name="entitySetName">Represents the entity set name, which may optionally be qualified by the entity container name. </param>
/// <param name="entity">
/// The <see cref="T:System.Object" /> to add.
/// </param>
/// <exception cref="T:System.ArgumentNullException">The entity parameter is null or the entitySetName does not qualify.</exception>
public virtual void AddObject(string entitySetName, object entity)
{
Check.NotNull(entity, "entity");
Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity.");
ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid();
EntityEntry existingEntry;
var wrappedEntity = EntityWrapperFactory.WrapEntityUsingContextGettingEntry(entity, this, out existingEntry);
if (existingEntry == null)
{
// If the exact object being added is already in the context, there there is no way we need to
// load the type for it, and since this is expensive, we only do the load if we have to.
// SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace.
// If the schema types are not loaded: metadata, cache & query would be unable to reason about the type.
// We will auto-load the entity type's assembly into the ObjectItemCollection.
// We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient.
MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null);
}
else
{
Debug.Assert(
existingEntry.Entity == entity, "FindEntityEntry should return null if existing entry contains a different object.");
}
EntitySet entitySet;
bool isNoOperation;
VerifyRootForAdd(false, entitySetName, wrappedEntity, existingEntry, out entitySet, out isNoOperation);
if (isNoOperation)
{
return;
}
var transManager = ObjectStateManager.TransactionManager;
transManager.BeginAddTracking();
try
{
var relationshipManager = wrappedEntity.RelationshipManager;
Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager");
var doCleanup = true;
try
{
// Add the root of the graph to the cache.
AddSingleObject(entitySet, wrappedEntity, "entity");
doCleanup = false;
}
finally
{
// If we failed after adding the entry but before completely attaching the related ends to the context, we need to do some cleanup.
// If the context is null, we didn't even get as far as trying to attach the RelationshipManager, so something failed before the entry
// was even added, therefore there is nothing to clean up.
if (doCleanup && wrappedEntity.Context == this)
{
// If the context is not null, it be because the failure happened after it was attached, or it
// could mean that this entity was already attached, in which case we don't want to clean it up
// If we find the entity in the context and its key is temporary, we must have just added it, so remove it now.
var entry = ObjectStateManager.FindEntityEntry(wrappedEntity.Entity);
if (entry != null
&& entry.EntityKey.IsTemporary)
{
// devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe
relationshipManager.NodeVisited = true;
// devnote: even though we haven't added the rest of the graph yet, we need to go through the related ends and
// clean them up, because some of them could have been attached to the context before the failure occurred
RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(wrappedEntity);
RelatedEnd.RemoveEntityFromObjectStateManager(wrappedEntity);
}
// else entry was not added or the key is not temporary, so it must have already been in the cache before we tried to add this product, so don't remove anything
}
}
relationshipManager.AddRelatedEntitiesToObjectStateManager( /*doAttach*/false);
}
finally
{
transManager.EndAddTracking();
ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid();
}
}
/// <summary>
/// Adds an object to the cache without adding its related
/// entities.
/// </summary>
/// <param name="entity"> Object to be added. </param>
/// <param name="setName"> EntitySet name for the Object to be added. It may be qualified with container name </param>
/// <param name="containerName"> Container name for the Object to be added. </param>
/// <param name="argumentName"> Name of the argument passed to a public method, for use in exceptions. </param>
internal void AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, string argumentName)
{
DebugCheck.NotNull(entitySet);
DebugCheck.NotNull(wrappedEntity);
DebugCheck.NotNull(wrappedEntity.Entity);
var key = wrappedEntity.GetEntityKeyFromEntity();
if (null != (object)key)
{
EntityUtil.ValidateEntitySetInKey(key, entitySet);
key.ValidateEntityKey(_workspace, entitySet);
}
VerifyContextForAddOrAttach(wrappedEntity);
wrappedEntity.Context = this;
var entry = ObjectStateManager.AddEntry(wrappedEntity, null, entitySet, argumentName, true);
// If the entity supports relationships, AttachContext on the
// RelationshipManager object - with load option of
// AppendOnly (if adding a new object to a context, set
// the relationships up to cache by default -- load option
// is only set to other values when AttachContext is
// called by the materializer). Also add all related entitites to
// cache.
//
// NOTE: AttachContext must be called after adding the object to
// the cache--otherwise the object might not have a key
// when the EntityCollections expect it to.
Debug.Assert(
ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding.");
Debug.Assert(ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set.");
ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity);
wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly);
// Find PK values in referenced principals and use these to set FK values
entry.FixupFKValuesFromNonAddedReferences();
ObjectStateManager.FixupReferencesByForeignKeys(entry);
wrappedEntity.TakeSnapshotOfRelationships(entry);
}
/// <summary>Explicitly loads an object related to the supplied object by the specified navigation property and using the default merge option. </summary>
/// <param name="entity">The entity for which related objects are to be loaded.</param>
/// <param name="navigationProperty">The name of the navigation property that returns the related objects to be loaded.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The entity is in a <see cref="F:System.Data.Entity.EntityState.Detached" />,
/// <see
/// cref="F:System.Data.Entity.EntityState.Added," />
/// or <see cref="F:System.Data.Entity.EntityState.Deleted" /> state or the entity is attached to another instance of
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </exception>
public virtual void LoadProperty(object entity, string navigationProperty)
{
var wrappedEntity = WrapEntityAndCheckContext(entity, "property");
wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load();
}
/// <summary>Explicitly loads an object that is related to the supplied object by the specified navigation property and using the specified merge option. </summary>
/// <param name="entity">The entity for which related objects are to be loaded.</param>
/// <param name="navigationProperty">The name of the navigation property that returns the related objects to be loaded.</param>
/// <param name="mergeOption">
/// The <see cref="T:System.Data.Entity.Core.Objects.MergeOption" /> value to use when you load the related objects.
/// </param>
/// <exception cref="T:System.InvalidOperationException">
/// The entity is in a <see cref="F:System.Data.Entity.EntityState.Detached" />,
/// <see
/// cref="F:System.Data.Entity.EntityState.Added," />
/// or <see cref="F:System.Data.Entity.EntityState.Deleted" /> state or the entity is attached to another instance of
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </exception>
public virtual void LoadProperty(object entity, string navigationProperty, MergeOption mergeOption)
{
var wrappedEntity = WrapEntityAndCheckContext(entity, "property");
wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load(mergeOption);
}
/// <summary>Explicitly loads an object that is related to the supplied object by the specified LINQ query and by using the default merge option. </summary>
/// <param name="entity">The source object for which related objects are to be loaded.</param>
/// <param name="selector">A LINQ expression that defines the related objects to be loaded.</param>
/// <typeparam name="TEntity"></typeparam>
/// <exception cref="T:System.ArgumentException"> selector does not supply a valid input parameter.</exception>
/// <exception cref="T:System.ArgumentNullException"> selector is null.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The entity is in a <see cref="F:System.Data.Entity.EntityState.Detached" />,
/// <see
/// cref="F:System.Data.Entity.EntityState.Added," />
/// or <see cref="F:System.Data.Entity.EntityState.Deleted" /> state or the entity is attached to another instance of
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public virtual void LoadProperty<TEntity>(TEntity entity, Expression<Func<TEntity, object>> selector)
{
// We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert,
// but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change.
// Therefore, we keep track of whether or not we removed the convert.
bool removedConvert;
var navProp = ParsePropertySelectorExpression(selector, out removedConvert);
var wrappedEntity = WrapEntityAndCheckContext(entity, "property");
wrappedEntity.RelationshipManager.GetRelatedEnd(navProp, throwArgumentException: removedConvert).Load();
}
/// <summary>Explicitly loads an object that is related to the supplied object by the specified LINQ query and by using the specified merge option. </summary>
/// <param name="entity">The source object for which related objects are to be loaded.</param>
/// <param name="selector">A LINQ expression that defines the related objects to be loaded.</param>
/// <param name="mergeOption">
/// The <see cref="T:System.Data.Entity.Core.Objects.MergeOption" /> value to use when you load the related objects.
/// </param>
/// <typeparam name="TEntity"></typeparam>
/// <exception cref="T:System.ArgumentException"> selector does not supply a valid input parameter.</exception>
/// <exception cref="T:System.ArgumentNullException"> selector is null.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The entity is in a <see cref="F:System.Data.Entity.EntityState.Detached" />,
/// <see
/// cref="F:System.Data.Entity.EntityState.Added," />
/// or <see cref="F:System.Data.Entity.EntityState.Deleted" /> state or the entity is attached to another instance of
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public virtual void LoadProperty<TEntity>(TEntity entity, Expression<Func<TEntity, object>> selector, MergeOption mergeOption)
{
// We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert,
// but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change.
// Therefore, we keep track of whether or not we removed the convert.
bool removedConvert;
var navProp = ParsePropertySelectorExpression(selector, out removedConvert);
var wrappedEntity = WrapEntityAndCheckContext(entity, "property");
wrappedEntity.RelationshipManager.GetRelatedEnd(navProp, throwArgumentException: removedConvert).Load(mergeOption);
}
// Wraps the given entity and checks that it has a non-null context (i.e. that is is not detached).
private IEntityWrapper WrapEntityAndCheckContext(object entity, string refType)
{
var wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entity, this);
if (wrappedEntity.Context == null)
{
throw new InvalidOperationException(Strings.ObjectContext_CannotExplicitlyLoadDetachedRelationships(refType));
}
if (wrappedEntity.Context
!= this)
{
throw new InvalidOperationException(Strings.ObjectContext_CannotLoadReferencesUsingDifferentContext(refType));
}
return wrappedEntity;
}
// Validates that the given property selector may represent a navigation property and returns the nav prop string.
// The actual check that the navigation property is valid is performed by the
// RelationshipManager while loading the RelatedEnd.
internal static string ParsePropertySelectorExpression<TEntity>(Expression<Func<TEntity, object>> selector, out bool removedConvert)
{
Check.NotNull(selector, "selector");
// We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert,
// but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change.
// Therefore, we keep track of whether or not we removed the convert.
removedConvert = false;
var body = selector.Body;
while (body.NodeType == ExpressionType.Convert
|| body.NodeType == ExpressionType.ConvertChecked)
{
removedConvert = true;
body = ((UnaryExpression)body).Operand;
}
var bodyAsMember = body as MemberExpression;
if (bodyAsMember == null
|| !bodyAsMember.Member.DeclaringType.IsAssignableFrom(typeof(TEntity))
|| bodyAsMember.Expression.NodeType != ExpressionType.Parameter)
{
throw new ArgumentException(Strings.ObjectContext_SelectorExpressionMustBeMemberAccess);
}
return bodyAsMember.Member.Name;
}
/// <summary>Applies property changes from a detached object to an object already attached to the object context.</summary>
/// <param name="entitySetName">The name of the entity set to which the object belongs.</param>
/// <param name="changed">The detached object that has property updates to apply to the original object.</param>
/// <exception cref="T:System.ArgumentNullException">When entitySetName is null or an empty string or when changed is null.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// When the <see cref="T:System.Data.Entity.Core.Metadata.Edm.EntitySet" /> from entitySetName does not match the
/// <see
/// cref="T:System.Data.Entity.Core.Metadata.Edm.EntitySet" />
/// of the object’s
/// <see
/// cref="T:System.Data.Entity.Core.EntityKey" />
/// or Wwen the entity is in a state other than
/// <see
/// cref="F:System.Data.Entity.EntityState.Modified" />
/// or
/// <see
/// cref="F:System.Data.Entity.EntityState.Unchanged" />
/// or the original object is not attached to the context.
/// </exception>
/// <exception cref="T:System.ArgumentException">When the type of the changed object is not the same type as the original object.</exception>
[EditorBrowsable(EditorBrowsableState.Never)]
[Browsable(false)]
[Obsolete("Use ApplyCurrentValues instead")]
public virtual void ApplyPropertyChanges(string entitySetName, object changed)
{
Check.NotNull(changed, "changed");
Check.NotEmpty(entitySetName, "entitySetName");
ApplyCurrentValues(entitySetName, changed);
}
/// <summary>
/// Copies the scalar values from the supplied object into the object in the
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// that has the same key.
/// </summary>
/// <returns>The updated object.</returns>
/// <param name="entitySetName">The name of the entity set to which the object belongs.</param>
/// <param name="currentEntity">
/// The detached object that has property updates to apply to the original object. The entity key of currentEntity must match the
/// <see
/// cref="P:System.Data.Entity.Core.Objects.ObjectStateEntry.EntityKey" />
/// property of an entry in the
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectContext" />
/// .
/// </param>
/// <typeparam name="TEntity">The entity type of the object.</typeparam>
/// <exception cref="T:System.ArgumentNullException"> entitySetName or current is null.</exception>
/// <exception cref="T:System.InvalidOperationException">
/// The <see cref="T:System.Data.Entity.Core.Metadata.Edm.EntitySet" /> from entitySetName does not match the
/// <see
/// cref="T:System.Data.Entity.Core.Metadata.Edm.EntitySet" />
/// of the object’s
/// <see
/// cref="T:System.Data.Entity.Core.EntityKey" />
/// or the object is not in the
/// <see
/// cref="T:System.Data.Entity.Core.Objects.ObjectStateManager" />
/// or it is in a
/// <see
/// cref="F:System.Data.Entity.EntityState.Detached" />
/// state or the entity key of the supplied object is invalid.
/// </exception>
/// <exception cref="T:System.ArgumentException"> entitySetName is an empty string.</exception>
public virtual TEntity ApplyCurrentValues<TEntity>(string entitySetName, TEntity currentEntity) where TEntity : class
{
Check.NotNull(currentEntity, "currentEntity");
Check.NotEmpty(entitySetName, "entitySetName");
var wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(currentEntity, this);
// SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace.
// If the schema types are not loaded: metadata, cache & query would be unable to reason about the type.
// We will auto-load the entity type's assembly into the ObjectItemCollection.
// We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient.
MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null);
var entitySet = GetEntitySetFromName(entitySetName);
var key = wrappedEntity.EntityKey;
if (null != (object)key)
{
EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName");
key.ValidateEntityKey(_workspace, entitySet);
}
else
{
key = ObjectStateManager.CreateEntityKey(entitySet, currentEntity);
}