コード例 #1
0
            public virtual void Explicit_principal_key_is_not_replaced_with_new_primary_key()
            {
                var model = new Model();
                var modelBuilder = CreateModelBuilder(model);
                modelBuilder
                    .Entity<BigMak>().HasMany(e => e.Pickles).WithOne(e => e.BigMak)
                    .PrincipalKey(e => new { e.Id });
                modelBuilder.Ignore<Bun>();

                var principalType = model.GetEntityType(typeof(BigMak));
                var dependentType = model.GetEntityType(typeof(Pickle));

                var nonPrimaryPrincipalKey = principalType.GetKeys().Single();

                var dependentKey = dependentType.GetKeys().SingleOrDefault();

                var modelClone = model.Clone();
                var expectedPrincipalProperties = modelClone.GetEntityType(typeof(BigMak)).GetProperties().ToList();
                var expectedDependentProperties = modelClone.GetEntityType(typeof(Pickle)).GetProperties().ToList();

                modelBuilder.Entity<BigMak>().HasKey(e => e.AlternateKey);

                var principalProperty = principalType.GetProperty("AlternateKey");
                var fk = dependentType.GetForeignKeys().Single();
                Assert.Same(nonPrimaryPrincipalKey, fk.PrincipalKey);

                Assert.Equal("BigMak", dependentType.Navigations.Single().Name);
                Assert.Equal("Pickles", principalType.Navigations.Single().Name);
                Assert.Same(fk, dependentType.Navigations.Single().ForeignKey);
                Assert.Same(fk, principalType.Navigations.Single().ForeignKey);
                AssertEqual(expectedPrincipalProperties.Select(p => p.Name), principalType.Properties.Select(p => p.Name));
                AssertEqual(expectedDependentProperties, dependentType.Properties);
                Assert.Empty(principalType.GetForeignKeys());

                var primaryPrincipalKey = principalType.GetPrimaryKey();
                Assert.Same(principalProperty, primaryPrincipalKey.Properties.Single());
                Assert.Equal(2, principalType.GetKeys().Count());
                Assert.True(principalType.GetKeys().Contains(nonPrimaryPrincipalKey));
                var oldKeyProperty = principalType.GetProperty(nameof(BigMak.Id));
                var newKeyProperty = principalType.GetProperty(nameof(BigMak.AlternateKey));
                Assert.True(oldKeyProperty.RequiresValueGenerator);
                Assert.Null(oldKeyProperty.ValueGenerated);
                Assert.True(newKeyProperty.RequiresValueGenerator);
                Assert.Equal(ValueGenerated.OnAdd, newKeyProperty.ValueGenerated);
                Assert.Same(dependentKey, dependentType.GetKeys().SingleOrDefault());
                Assert.Same(dependentKey, dependentType.FindPrimaryKey());
            }