File: DbContextTests.cs

package info (click to toggle)
mono 3.2.8%2Bdfsg-10
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 527,964 kB
  • ctags: 623,327
  • sloc: cs: 3,938,236; xml: 1,891,753; ansic: 418,737; java: 59,920; sh: 15,754; makefile: 11,067; sql: 7,956; perl: 2,279; cpp: 1,380; yacc: 1,203; python: 594; asm: 422; sed: 16; php: 1
file content (740 lines) | stat: -rw-r--r-- 28,590 bytes parent folder | download | duplicates (2)
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
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

namespace ProductivityApiUnitTests
{
    using System;
    using System.Collections.Generic;
    using System.Data.Common;
    using System.Data.Entity;
    using System.Data.Entity.Core.EntityClient;
    using System.Data.Entity.Core.Objects;
    using System.Data.Entity.Infrastructure;
    using System.Data.Entity.Internal;
    using System.Data.Entity.Migrations.Utilities;
    using System.Data.Entity.ModelConfiguration.Edm;
    using System.Data.Entity.ModelConfiguration.Internal.UnitTests;
    using System.Data.Entity.Resources;
    using System.Data.SqlClient;
    using System.Data.SqlServerCe;
    using System.Linq;
    using Moq;
    using Moq.Protected;
    using Xunit;

    #region Context types for testing database name generation

    internal class SimpleContextClass : DbContext
    {
        internal class NestedContextClass : DbContext
        {
            internal class DouubleNestedContextClass : DbContext
            {
            }
        }

        internal class GenericContextClass<T> : DbContext
        {
        }

        internal class DoubleGenericContextClass<T1, T2> : DbContext
        {
        }
    }

    internal class GenericContextClass<T> : DbContext
    {
        internal class NestedContextClass : DbContext
        {
        }
    }

    internal class DoubleGenericContextClass<T1, T2> : DbContext
    {
        internal class NestedContextClass : DbContext
        {
        }

        internal class DoubleGenericNestedContextClass<T3, T4> : DbContext
        {
            internal class DoubleGenericDoubleNestedContextClass<T5, T6> : DbContext
            {
            }
        }
    }

    #endregion

    /// <summary>
    ///     Unit tests for DbContext.
    /// </summary>
    public class DbContextTests : TestBase
    {
        static DbContextTests()
        {
            // Ensure the basic-auth test user exists

            using (var connection = new SqlConnection(SimpleConnectionString("master")))
            {
                connection.Open();

                using (var command = connection.CreateCommand())
                {
                    command.CommandText
                        = @"IF NOT EXISTS (SELECT * FROM sys.server_principals WHERE name = N'EFTestUser')
BEGIN
  CREATE LOGIN [EFTestUser] WITH PASSWORD=N'Password1', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF
  EXEC sys.sp_addsrvrolemember @loginame = N'EFTestUser', @rolename = N'sysadmin'
END";
                    command.ExecuteNonQuery();
                }
            }
        }

        #region Using EF connection string/EntityConnection in combination with DbCompiledModel

        private const string EntityConnectionString =
            @"metadata=.\Foo.csdl|.\Foo.ssdl|.\Foo.msl;provider=System.Data.SqlClient;provider connection string='Server=.\Foo;Database=Bar'";

        private static DbCompiledModel _emptyModel;

        private static DbCompiledModel EmptyModel
        {
            get { return _emptyModel ?? (_emptyModel = new DbModelBuilder().Build(ProviderRegistry.Sql2008_ProviderInfo).Compile()); }
        }

        [Fact]
        public void Entity_connection_string_and_DbCompiledModel_used_together_throw()
        {
            using (var context = new DbContext(EntityConnectionString, EmptyModel))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionHasModel,
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        [Fact]
        public void Named_entity_connection_string_and_DbCompiledModel_used_together_throw()
        {
            using (var context = new DbContext("EntityConnectionString", EmptyModel))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionHasModel,
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        [Fact]
        public void Named_entity_connection_string_using_name_keyword_and_DbCompiledModel_used_together_throw()
        {
            using (var context = new DbContext("name=EntityConnectionString", EmptyModel))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionHasModel,
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        [Fact]
        public void EntitConnection_object_and_DbCompiledModel_used_together_throw()
        {
            using (var context = new DbContext(new EntityConnection(EntityConnectionString), EmptyModel, contextOwnsConnection: true))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionHasModel,
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        #endregion

        #region Bad connection string tests

        [Fact]
        public void Using_name_keyword_throws_if_name_not_found_in_app_config()
        {
            using (var context = new FakeDerivedDbContext("name=MissingConnectionString"))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionStringNotFound("MissingConnectionString"),
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        [Fact]
        public void Using_name_keyword_throws_if_name_not_found_in_app_config_even_if_DbCompiledModel_passed()
        {
            using (var context = new DbContext("name=MissingConnectionString", EmptyModel))
            {
                Assert.Equal(
                    Strings.DbContext_ConnectionStringNotFound("MissingConnectionString"),
                    Assert.Throws<InvalidOperationException>(() => context.Set<FakeEntity>().Load()).Message);
            }
        }

        #endregion

        #region Negative constructor tests

        [Fact]
        public void Constructing_DbContext_with_null_nameOrConnectionString_throws()
        {
            Assert.Equal(
                Strings.ArgumentIsNullOrWhitespace("nameOrConnectionString"),
                Assert.Throws<ArgumentException>(() => new FakeDerivedDbContext((string)null)).Message);
        }

        [Fact]
        public void Constructing_DbContext_with_empty_nameOrConnectionString_throws()
        {
            Assert.Equal(
                Strings.ArgumentIsNullOrWhitespace("nameOrConnectionString"),
                Assert.Throws<ArgumentException>(() => new FakeDerivedDbContext("")).Message);
        }

        [Fact]
        public void Constructing_DbContext_with_whitespace_nameOrConnectionString_throws()
        {
            Assert.Equal(
                Strings.ArgumentIsNullOrWhitespace("nameOrConnectionString"),
                Assert.Throws<ArgumentException>(() => new FakeDerivedDbContext(" ")).Message);
        }

        [Fact]
        public void Constructing_DbContext_with_null_existingConnection_throws()
        {
            Assert.Equal(
                "existingConnection", Assert.Throws<ArgumentNullException>(() => new FakeDerivedDbContext((DbConnection)null)).ParamName);
        }

        [Fact]
        public void Constructing_DbContext_with_null_objectContext_throws()
        {
            Assert.Equal(
                "objectContext",
                Assert.Throws<ArgumentNullException>(() => new DbContext(null, dbContextOwnsObjectContext: false)).ParamName);
        }

        [Fact]
        public void Constructing_DbContext_with_null_model_using_model_only_constructor_throws()
        {
            Assert.Equal("model", Assert.Throws<ArgumentNullException>(() => new FakeDerivedDbContext((DbCompiledModel)null)).ParamName);
        }

        [Fact]
        public void Constructing_DbContext_with_null_model_using_nameOrConnectionString_constructor_throws()
        {
            Assert.Equal("model", Assert.Throws<ArgumentNullException>(() => new DbContext("Johnny Rotten", null)).ParamName);
        }

        [Fact]
        public void Constructing_DbContext_with_null_model_using_existingConnection_constructor_throws()
        {
            Assert.Equal(
                "model",
                Assert.Throws<ArgumentNullException>(() => new DbContext(new SqlConnection(), null, contextOwnsConnection: false)).ParamName);
        }

        #endregion

        #region Virtual Dispose tests

        [Fact]
        public void Dispose_can_be_overriden_in_a_derived_DbContext()
        {
            var mockContext = new Mock<DbContext>();
            mockContext.Protected().Setup("Dispose", true).Verifiable();

            mockContext.Object.Dispose();

            mockContext.Verify();
        }

        #endregion

        #region Tests for DbModelBuilderVersionAttribute

        [Fact]
        public void DbModelBuilderVersion_Latest_is_used_if_no_attribute_is_provided()
        {
            var internalContext = new LazyInternalContext(
                new Mock<DbContext>().Object,
                new Mock<IInternalConnection>().Object, null);

            var builder = internalContext.CreateModelBuilder();

            Assert.Equal(DbModelBuilderVersion.Latest, builder.Version);
        }

        [Fact]
        public void Can_read_version_from_DbModelBuilderVersionAttribute()
        {
            var attribute = new DbModelBuilderVersionAttribute(DbModelBuilderVersion.Latest);

            Assert.Equal(DbModelBuilderVersion.Latest, attribute.Version);
        }

        [DbModelBuilderVersion(DbModelBuilderVersion.V4_1)]
        public class FakeWithAttribute : DbContext
        {
        }

        [Fact]
        public void Version_in_DbModelBuilderVersionAttribute_is_used_if_provided()
        {
            var internalContext = new LazyInternalContext(new FakeWithAttribute(), new Mock<IInternalConnection>().Object, null);

            var builder = internalContext.CreateModelBuilder();

            Assert.Equal(DbModelBuilderVersion.V4_1, builder.Version);
        }

        [DbModelBuilderVersion(DbModelBuilderVersion.Latest)]
        public class FakeWithAttributeDerived : FakeWithAttribute
        {
        }

        [Fact]
        public void Version_from_DbModelBuilderVersionAttribute_on_derived_context_overrides_version_from_base()
        {
            var internalContext = new LazyInternalContext(new FakeWithAttributeDerived(), new Mock<IInternalConnection>().Object, null);

            var builder = internalContext.CreateModelBuilder();

            Assert.Equal(DbModelBuilderVersion.Latest, builder.Version);
        }

        public class FakeWithNoAttributeDerived : FakeWithAttribute
        {
        }

        [Fact]
        public void Version_from_DbModelBuilderVersionAttribute_on_base_context_is_used_if_no_attribute_is_found_on_derived_context()
        {
            var internalContext = new LazyInternalContext(new FakeWithNoAttributeDerived(), new Mock<IInternalConnection>().Object, null);

            var builder = internalContext.CreateModelBuilder();

            Assert.Equal(DbModelBuilderVersion.V4_1, builder.Version);
        }

        #endregion

        #region Tests for creating database names from context class names

        [Fact]
        public void Simple_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.SimpleContextClass",
                typeof(SimpleContextClass).DatabaseName());
        }

        [Fact]
        public void Nested_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.SimpleContextClass+NestedContextClass",
                typeof(SimpleContextClass.NestedContextClass).DatabaseName());
        }

        [Fact]
        public void Double_nested_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.SimpleContextClass+NestedContextClass+DouubleNestedContextClass",
                typeof(SimpleContextClass.NestedContextClass.DouubleNestedContextClass).DatabaseName());
        }

        [Fact]
        public void Generic_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.GenericContextClass`1[System.String]",
                typeof(GenericContextClass<string>).DatabaseName());
        }

        [Fact]
        public void Double_generic_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.DoubleGenericContextClass`2[System.String,System.Int32]",
                typeof(DoubleGenericContextClass<string, int>).DatabaseName());
        }

        [Fact]
        public void Nested_in_generic_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.GenericContextClass`1+NestedContextClass[System.String]",
                typeof(GenericContextClass<string>.NestedContextClass).DatabaseName());
        }

        [Fact]
        public void Nested_in_double_generic_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.DoubleGenericContextClass`2+NestedContextClass[System.String,System.Int32]",
                typeof(DoubleGenericContextClass<string, int>.NestedContextClass).DatabaseName());
        }

        [Fact]
        public void Double_generic_double_nested_in_double_generic_context_class_can_be_used_to_create_database_name()
        {
            Assert.Equal(
                "ProductivityApiUnitTests.DoubleGenericContextClass`2+DoubleGenericNestedContextClass`2+DoubleGenericDoubleNestedContextClass`2[System.String,System.Int32,System.Collections.Generic.ICollection`1[System.String],System.Random,System.Collections.Generic.Dictionary`2[System.String,System.Int32],System.Nullable`1[System.Int32]]",
                typeof(
                    DoubleGenericContextClass<string, int>.DoubleGenericNestedContextClass<ICollection<string>, Random>.
                        DoubleGenericDoubleNestedContextClass<Dictionary<string, int>, int?>).DatabaseName());
        }

        #endregion

        #region PersistSecurityInfo tests

        private class PersistSecurityInfoContext : DbContext
        {
            static PersistSecurityInfoContext()
            {
                Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PersistSecurityInfoContext>());
            }

            public PersistSecurityInfoContext(string nameOrConnectionString)
                : base(nameOrConnectionString)
            {
            }

            public PersistSecurityInfoContext(DbConnection existingConnection, bool contextOwnsConnection)
                : base(existingConnection, contextOwnsConnection)
            {
            }

            public PersistSecurityInfoContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
                : base(objectContext, dbContextOwnsObjectContext)
            {
            }

            public IDbSet<PersistEntity> Entities { get; set; }

            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<PersistEntity>().ToTable(DateTime.Now.Ticks.ToString());
            }
        }

        [Fact]
        public void Can_initialize_database_when_using_secure_connection_string_with_sql_server_authentication_and_lazy_connection()
        {
            var connectionString
                = SimpleConnectionStringWithCredentials(
                    "PersistSecurityInfoContext",
                    "EFTestUser",
                    "Password1");

            var context = new PersistSecurityInfoContext(connectionString);

            try
            {
                context.Database.Initialize(true);
            }
            finally
            {
                context.Database.Delete();
            }

            Assert.Equal(
                new SqlConnectionStringBuilder(connectionString).Password,
                new SqlConnectionStringBuilder(context.Database.Connection.ConnectionString).Password);
        }

        [Fact]
        public void Can_initialize_database_when_using_secure_connection_string_with_sql_server_authentication_and_eager_connection()
        {
            var connectionString
                = SimpleConnectionStringWithCredentials(
                    "PersistSecurityInfoContext",
                    "EFTestUser",
                    "Password1");

            var context = new PersistSecurityInfoContext(new SqlConnection(connectionString), true);

            try
            {
                context.Database.Delete();

                context.Database.Initialize(true);
            }
            finally
            {
                context.Database.Delete();
            }

            Assert.Equal(
                new SqlConnectionStringBuilder(connectionString).Password,
                new SqlConnectionStringBuilder(context.Database.Connection.ConnectionString).Password);
        }

        [Fact]
        public void Can_use_ddl_ops_when_using_secure_connection_string_with_sql_server_authentication_and_eager_context()
        {
            var connectionString
                = SimpleConnectionStringWithCredentials(
                    "PersistSecurityInfoContext",
                    "EFTestUser",
                    "Password1");

            var modelBuilder = new DbModelBuilder();
            modelBuilder.Entity<PersistEntity>().ToTable(DateTime.Now.Ticks.ToString());
            var model = modelBuilder.Build(ProviderRegistry.Sql2008_ProviderInfo);
            var entityConnection
                = new EntityConnection(model.DatabaseMapping.ToMetadataWorkspace(), new SqlConnection(connectionString));

            var objectContext = new ObjectContext(entityConnection);

            var context = new PersistSecurityInfoContext(objectContext, true);

            try
            {
                context.Database.Delete();

                context.Database.Create();
                
                Assert.Equal(
                    new SqlConnectionStringBuilder(connectionString).Password,
                    new SqlConnectionStringBuilder(context.Database.Connection.ConnectionString).Password);

                context.Set<PersistEntity>().ToList();

                context.Database.Delete();
            }
            finally
            {
                context.Database.Delete();
            }
        }

        #endregion

        #region Replace connection tests

        [Fact]
        public void Can_replace_connection()
        {
            var intializer = new ReplaceConnectionInitializer();
            Database.SetInitializer(intializer);

            using (var context = new ReplaceConnectionContext())
            {
                using (var newConnection =
                    new LazyInternalConnection(
                        new DbConnectionInfo(
                            @"Server=.\SQLEXPRESS;Database=NewReplaceConnectionContextDatabase;Trusted_Connection=True;",
                            "System.Data.SqlClient")))
                {
                    context.InternalContext.OverrideConnection(newConnection);

                    Assert.IsType<SqlConnection>(context.Database.Connection);
                    Assert.Equal("NewReplaceConnectionContextDatabase", context.Database.Connection.Database);

                    context.Database.Initialize(force: true);
                    Assert.Equal(
                        "NewReplaceConnectionContextDatabase",
                        intializer.DatabaseNameUsedDuringInitialization);
                }
            }
        }

        [Fact]
        public void Can_replace_connection_with_different_provider()
        {
            var intializer = new ReplaceConnectionInitializer();
            Database.SetInitializer(intializer);

            using (var context = new ReplaceConnectionContext())
            {
                using (var newConnection =
                    new LazyInternalConnection(
                        new DbConnectionInfo(
                            "Data Source=NewReplaceConnectionContextDatabase.sdf",
                            "System.Data.SqlServerCe.4.0")))
                {
                    context.InternalContext.OverrideConnection(newConnection);

                    Assert.IsType<SqlCeConnection>(context.Database.Connection);
                    Assert.Equal(
                        "NewReplaceConnectionContextDatabase.sdf",
                        context.Database.Connection.Database);

                    context.Database.Initialize(force: true);
                    Assert.Equal(
                        "NewReplaceConnectionContextDatabase.sdf",
                        intializer.DatabaseNameUsedDuringInitialization);
                }
            }
        }

        [Fact]
        public void Exception_replacing_DbConnection_with_EntityConnection()
        {
            using (var context = new ReplaceConnectionContext())
            {
                using (var newConnection = new EagerInternalConnection(new EntityConnection(), connectionOwned: true))
                {
                    Assert.Equal(
                        Strings.LazyInternalContext_CannotReplaceDbConnectionWithEfConnection,
                        Assert.Throws<InvalidOperationException>(() => context.InternalContext.OverrideConnection(newConnection)).Message);
                }
            }
        }

        [Fact]
        public void Exception_replacing_EntityConnection_with_DbConnection()
        {
            using (var context = new ReplaceConnectionContext("name=EntityConnectionString"))
            {
                using (var newConnection = new LazyInternalConnection("ByConventionName"))
                {
                    Assert.Equal(
                        Strings.LazyInternalContext_CannotReplaceEfConnectionWithDbConnection,
                        Assert.Throws<InvalidOperationException>(() => context.InternalContext.OverrideConnection(newConnection)).Message);
                }
            }
        }

        [Fact]
        public void Exception_replacing_connection_on_eager_context()
        {
            using (var connection = new SqlConnection(@"Server=.\SQLEXPRESS;Database=MigrationInitFromConfig;Trusted_Connection=True;"))
            {
                var ctx = new DbModelBuilder()
                    .Build(connection)
                    .Compile()
                    .CreateObjectContext<ObjectContext>(connection);

                using (var context = new DbContext(ctx, dbContextOwnsObjectContext: true))
                {
                    using (var newConnection = new LazyInternalConnection("ByConventionName"))
                    {
                        Assert.Equal(
                            Strings.EagerInternalContext_CannotSetConnectionInfo,
                            Assert.Throws<InvalidOperationException>(() => context.InternalContext.OverrideConnection(newConnection)).
                                   Message);
                    }
                }
            }
        }

        [Fact]
        public void Replacing_connection_does_not_initialize_either_connection()
        {
            using (var origConnection = new LazyInternalConnection("OrigName"))
            {
                using (var newConnection = new LazyInternalConnection("NewName"))
                {
                    var context = new LazyInternalContext(new ReplaceConnectionContext(), origConnection, null);
                    context.OverrideConnection(newConnection);

                    Assert.False(origConnection.IsInitialized);
                    Assert.False(newConnection.IsInitialized);
                }
            }
        }

        public class ReplaceConnectionContext : DbContext
        {
            public ReplaceConnectionContext()
            {
            }

            public ReplaceConnectionContext(string nameOrConnectionString)
                : base(nameOrConnectionString)
            {
            }
        }

        public class ReplaceConnectionInitializer : IDatabaseInitializer<ReplaceConnectionContext>
        {
            public string DatabaseNameUsedDuringInitialization { get; set; }

            public void InitializeDatabase(ReplaceConnectionContext context)
            {
                if (DatabaseNameUsedDuringInitialization != null)
                {
                    throw new Exception("Initialization already performed!");
                }

                DatabaseNameUsedDuringInitialization = context.Database.Connection.Database;
            }
        }

        #endregion

        #region Provider tests

        [Fact]
        public void ProviderName_gets_name_from_DbConnection_when_eager_context_is_used()
        {
            var mockContext = new Mock<EagerInternalContext>(new Mock<DbContext>().Object)
                                  {
                                      CallBase = true
                                  };
            mockContext.Setup(m => m.Connection).Returns(new SqlConnection());

            Assert.Equal("System.Data.SqlClient", mockContext.Object.ProviderName);
            mockContext.Verify(m => m.Connection, Times.Once());
        }

        [Fact]
        public void ProviderName_gets_name_from_internal_connection_ProviderName_when_lazy_context_is_used()
        {
            var mockConnection = new Mock<IInternalConnection>();
            var mockContext = new Mock<LazyInternalContext>(new Mock<DbContext>().Object, mockConnection.Object, null, null)
                                  {
                                      CallBase = true
                                  };
            mockConnection.Setup(m => m.ProviderName).Returns("SomeLazyProvider");

            Assert.Equal("SomeLazyProvider", mockContext.Object.ProviderName);
            mockContext.Verify(m => m.Connection, Times.Never());
        }

        [Fact]
        public void Can_get_metadata_with_minimal_DbConnection_implementation()
        {
            // Required for use with MVC Scaffolding that uses Microsoft.VisualStudio.Web.Mvc.Scaffolding.BuiltIn.ScaffoldingDbConnection
            // which is a very minimal implementation of DbConnection.
            using (var connection = new FakeSqlConnection
                                        {
                                            ConnectionString = ""
                                        })
            {
                using (var context = new EmptyContext(connection))
                {
                    var metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
                    Assert.NotNull(metadata);
                }
            }
        }

        #endregion

        #region Set tests

        [Fact]
        public void Passing_null_type_to_Non_generic_Set_method_throws()
        {
            var context = new Mock<InternalContextForMock>
                              {
                                  CallBase = true
                              }.Object.Owner;
            Assert.Equal("entityType", Assert.Throws<ArgumentNullException>(() => context.Set(null)).ParamName);
        }

        #endregion
    }

    public class PersistEntity
    {
        public int Id { get; set; }
    }
}