Exemplo n.º 1
0
        public void UseTwoDifferentContexts()
        {
            using (var ctx1 = new MyTestDbContext())
            {
                ctx1.SetupAsTestDbContext();

                var p1 = new Person { Name = "Jürgen" };
                p1.Addresses.Add(new Adresse { Name = "AlterWert1" });
                p1.Addresses.Add(new Adresse { Name = "AlterWert2" });
                ctx1.Persons.Add(p1);
                ctx1.SaveChanges();
            }

            using (var ctx2 = new MyTestDbContext())
            {
                ctx2.SetupAsTestDbContext();
                var persons = ctx2.Persons;

                Assert.AreEqual(2, persons.First().Addresses.Count());
            }

            Person p2;
            using (var ctx3 = new MyTestDbContext())
            {
                ctx3.SetupAsTestDbContext();
                p2 = ctx3.Persons.FirstOrDefault(x => x.Id == 1);
                p2.Name = "ÜberschriebenerWert";
                p2.Addresses.First().Name = "Hallo";
            }

            using (var ctx4 = new MyTestDbContext())
            {
                ctx4.SetupAsTestDbContext();
                ctx4.Entry(p2).State = EntityState.Modified;
                ctx4.SaveChanges();
            }

            using (var ctx5 = new MyTestDbContext())
            {
                ctx5.SetupAsTestDbContext();
                var p3 = ctx5.Persons.FirstOrDefault(x => x.Id == 1);


                Assert.That(p2, Is.Not.EqualTo(p3));
                Assert.That(p3.Name, Is.EqualTo("ÜberschriebenerWert"));
                Assert.That(p3.Addresses.First().Name, Is.EqualTo("AlterWert1"));
            }
        }