Example #1
0
        public IQueryable DoQuery(string value)
        {
            string             queryOption = "$apply";
            var                data        = TestDataSource.CreateData();
            ODataQuerySettings settings    = new ODataQuerySettings()
            {
                PageSize = 2000, HandleNullPropagation = HandleNullPropagationOption.False
            };
            var model   = TestModelBuilder.CreateModel(new Type[] { typeof(Category), typeof(Product), typeof(Sales) });
            var context = new ODataQueryContext(model, typeof(Sales), new ODataPath(new ODataPathSegment[] { new EntitySetPathSegment("Sales") }));

            IEdmNavigationSource source = model.FindDeclaredEntitySet("Sales");
            var parser = new ODataQueryOptionParser(model,
                                                    model.FindDeclaredType("System.Web.OData.Aggregation.Tests.Common.Sales"),
                                                    source,
                                                    new Dictionary <string, string>()
            {
                { queryOption, value }
            });

            var applyClause  = parser.ParseApply();
            var filterClause = applyClause.Transformations.First().Item2 as ApplyFilterClause;

            var filter = new FilterImplementation()
            {
                Context = context
            };

            return(filter.DoFilter(data, filterClause, settings, parser));
        }
Example #2
0
        protected ApplyQueryOption GetApplyQueryOption(string query)
        {
            string             queryOption = "$apply";
            ODataQuerySettings settings    = new ODataQuerySettings()
            {
                PageSize = 2000,
                HandleNullPropagation = HandleNullPropagationOption.False
            };

            var model = TestModelBuilder.CreateModel(new Type[] { typeof(Category), typeof(Product), typeof(Sales) });

            var context = new ODataQueryContext(model, typeof(Sales),
                                                new ODataPath(new ODataPathSegment[] { new EntitySetPathSegment("Sales") }));

            IEdmNavigationSource source = model.FindDeclaredEntitySet("Sales");

            var queryOptionParser = new ODataQueryOptionParser(model,
                                                               model.FindDeclaredType("System.Web.OData.Aggregation.Tests.Common.Sales"),
                                                               source,
                                                               new Dictionary <string, string>()
            {
                { queryOption, query }
            });

            return(new ApplyQueryOption(context, queryOptionParser));
        }
        public async Task ThenTheStatusShouldBeFound()
        {
            // Arrange
            string hashedAccountId = null;
            await _tester.InitialiseData <EmployerAccountsDbBuilder>(async builder =>
            {
                var data = new TestModelBuilder()
                           .WithNewUser()
                           .WithNewAccount()
                           .WithNewLegalEntity();

                await builder.SetupDataAsync(data);

                hashedAccountId = data.CurrentAccount.AccountOutput.HashedAccountId;
            });

            var callRequirements =
                new CallRequirements($"api/accounts/{hashedAccountId}/legalentities");

            // Act
            var legalEntities = await _tester.InvokeGetAsync <ResourceList>(callRequirements);

            // Assert
            legalEntities.ExpectStatusCodes(HttpStatusCode.OK);
            legalEntities.ExpectControllerType(typeof(LegalEntitiesController));
            Assert.IsNotNull(legalEntities.Data);
        }
        public async Task ThenTheStatusShouldBeFound_AndDataShouldContainOnlyTheExpectedUser()
        {
            // Arrange
            string hashedAccountId = null;
            var    userRef         = Guid.Empty;

            await _tester.InitialiseData <EmployerAccountsDbBuilder>(async builder =>
            {
                var data = new TestModelBuilder()
                           .WithNewUser()
                           .WithNewAccount()
                           .WithNewLegalEntity();

                await builder.SetupDataAsync(data);

                hashedAccountId = data.CurrentAccount.AccountOutput.HashedAccountId;
                userRef         = data.CurrentUser.UserOutput.UserRef;
            });

            var callRequirements = new CallRequirements($"api/accounts/{hashedAccountId}/users");

            // Act
            var account = await _tester.InvokeGetAsync <ICollection <TeamMemberViewModel> >(callRequirements);

            // Assert

            account.ExpectControllerType(typeof(EmployerAccountsController));
            account.ExpectStatusCodes(HttpStatusCode.OK);
            Assert.IsNotNull(account.Data);
            Assert.AreEqual(1, account.Data.Count);
            Assert.AreEqual(userRef, Guid.Parse(account.Data.Last().UserRef));
        }
        public void Apply_should_correct_dangling_navigation_properties()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("A1", "S", RelationshipMultiplicity.ZeroOrOne, "T", "T", RelationshipMultiplicity.Many, null)
                    .Association("A2", "T", RelationshipMultiplicity.Many, "S", "S", RelationshipMultiplicity.ZeroOrOne, null);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            var navigationProperties
                = model.EntityTypes.SelectMany(e => e.NavigationProperties);

            Assert.Equal(2, navigationProperties.Count());

            var navigationProperty1 = navigationProperties.ElementAt(0);
            var navigationProperty2 = navigationProperties.ElementAt(1);
            var associationType = model.AssociationTypes.Single();

            Assert.Same(associationType, navigationProperty1.Association);
            Assert.Same(associationType, navigationProperty2.Association);
            Assert.Same(associationType.SourceEnd, navigationProperty1.FromEndMember);
            Assert.Same(associationType.TargetEnd, navigationProperty1.ResultEnd);
            Assert.Same(associationType.TargetEnd, navigationProperty2.FromEndMember);
            Assert.Same(associationType.SourceEnd, navigationProperty2.ResultEnd);
        }
        public void Apply_should_correct_dangling_navigation_properties()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S", "T")
                  .Association("A1", "S", RelationshipMultiplicity.ZeroOrOne, "T", "T", RelationshipMultiplicity.Many, null)
                  .Association("A2", "T", RelationshipMultiplicity.Many, "S", "S", RelationshipMultiplicity.ZeroOrOne, null);

            ((IEdmConvention) new AssociationInverseDiscoveryConvention()).Apply(model);

            var navigationProperties
                = model.EntityTypes.SelectMany(e => e.NavigationProperties);

            Assert.Equal(2, navigationProperties.Count());

            var navigationProperty1 = navigationProperties.ElementAt(0);
            var navigationProperty2 = navigationProperties.ElementAt(1);
            var associationType     = model.AssociationTypes.Single();

            Assert.Same(associationType, navigationProperty1.Association);
            Assert.Same(associationType, navigationProperty2.Association);
            Assert.Same(associationType.SourceEnd, navigationProperty1.FromEndMember);
            Assert.Same(associationType.TargetEnd, navigationProperty1.ResultEnd);
            Assert.Same(associationType.TargetEnd, navigationProperty2.FromEndMember);
            Assert.Same(associationType.SourceEnd, navigationProperty2.ResultEnd);
        }
        public void Apply_should_transfer_constraint_and_clr_property_info_annotation()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                    .Association("T", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne);

            var association2 = model.AssociationTypes.Last();

            var mockPropertyInfo = new MockPropertyInfo();
            association2.SourceEnd.SetClrPropertyInfo(mockPropertyInfo);

            var referentialConstraint 
                = new ReferentialConstraint(
                    association2.SourceEnd, 
                    association2.TargetEnd, 
                    new[] { new EdmProperty("P") }, 
                    new[] { new EdmProperty("D") });
            
            association2.Constraint = referentialConstraint;

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.NotSame(association2, associationType);
            Assert.Same(referentialConstraint, associationType.Constraint);
            Assert.Same(associationType.SourceEnd, referentialConstraint.FromRole);
            Assert.Same(associationType.TargetEnd, referentialConstraint.ToRole);
            Assert.Same(mockPropertyInfo.Object, associationType.TargetEnd.GetClrPropertyInfo());
        }
        public void OneTimeSetUp()
        {
            _sut = new SqlQueryBuilderWithObjectHierarchy('.');

            var edmModel      = TestModelBuilder.BuildModel();
            var edmSchemaType = edmModel.SchemaElements.FirstOrDefault(w => w.Name == TestModelBuilder.TestEntityName) as IEdmSchemaType;

            _oDataQueryContext = new ODataQueryContext(edmModel, edmSchemaType);
        }
Example #9
0
        /// <summary>
        ///     Persists the data defined in <see cref="TestModelBuilder"/> to the database. Keys
        ///     will be propagated automatically. e.g. User Ids will be add to any accounts created
        ///     for that user;
        /// </summary>
        public async Task <EmployerAccountsDbBuilder> SetupDataAsync(TestModelBuilder builder)
        {
            foreach (var userSetup in builder.Users)
            {
                userSetup.UserOutput = await CreateUserAsync(userSetup.UserInput);

                await CreateAccountsForUserAsync(userSetup);
            }

            return(this);
        }
            public virtual void Weak_types_with_FK_to_another_entity_works(TestModelBuilder modelBuilder)
            {
                var ownerEntityTypeBuilder = modelBuilder.Entity <BillingOwner>();

                ownerEntityTypeBuilder.OwnsOne(e => e.Bill1,
                                               o => o.HasOne <Country>().WithMany().HasPrincipalKey(c => c.Name).HasForeignKey(d => d.Country));

                ownerEntityTypeBuilder.OwnsOne(e => e.Bill2,
                                               o => o.HasOne <Country>().WithMany().HasPrincipalKey(c => c.Name).HasForeignKey(d => d.Country));

                modelBuilder.Validate();
            }
Example #11
0
        protected static void GetApplyToParams(out ODataQuerySettings settings, out EdmModel model, out ODataQueryContext context, out IAssembliesResolver assembliesResolver)
        {
            settings = new ODataQuerySettings()
            {
                PageSize = 2000,
                HandleNullPropagation = HandleNullPropagationOption.False
            };

            assembliesResolver = new DefaultAssembliesResolver();
            model   = TestModelBuilder.CreateModel(new Type[] { typeof(Category), typeof(Product), typeof(Sales) });
            context = new ODataQueryContext(model, typeof(Sales),
                                            new ODataPath(new ODataPathSegment[] { new EntitySetPathSegment("Sales") }));
        }
        public void Apply_should_not_discover_when_too_many_associations()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S", "T")
                  .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                  .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                  .Association("T", RelationshipMultiplicity.ZeroOrOne, "S", RelationshipMultiplicity.Many);

            ((IEdmConvention) new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(3, model.AssociationTypes.Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
        public async Task Setup()
        {
            await InitialiseEmployerAccountData(async builder =>
            {
                var data = new TestModelBuilder()
                           .WithNewUser()
                           .WithNewAccount();

                await builder.SetupDataAsync(data);

                _employerAccount = data.CurrentAccount.AccountOutput;
            });

            WhenControllerActionIsCalled($"https://localhost:44330/api/accounts/{_employerAccount.HashedAccountId}/legalentities");
        }
        public async Task Setup()
        {
            _tester = new ApiIntegrationTester(TestSetupIoC.CreateIoC);

            // Arrange
            await _tester.InitialiseData <EmployerAccountsDbBuilder>(async builder =>
            {
                var data = new TestModelBuilder()
                           .WithNewUser()
                           .WithNewAccount();

                await builder.SetupDataAsync(data);

                _employerAccount = data.CurrentAccount.AccountOutput;
            });
        }
Example #15
0
            public static new IServiceCollection ConfigureApi(Type apiType, IServiceCollection services)
            {
                var modelBuilder = new TestModelBuilder();
                var modelMapper = new TestModelMapper();
                var querySourcer = new TestQuerySourcer();
                var changeSetPreparer = new TestChangeSetInitializer();
                var submitExecutor = new TestSubmitExecutor();

                services.AddCoreServices(apiType);
                services.AddService<IModelBuilder>((sp, next) => modelBuilder);
                services.AddService<IModelMapper>((sp, next) => modelMapper);
                services.AddService<IQueryExpressionSourcer>((sp, next) => querySourcer);
                services.AddService<IChangeSetInitializer>((sp, next) => changeSetPreparer);
                services.AddService<ISubmitExecutor>((sp, next) => submitExecutor);

                return services;
            }
Example #16
0
            protected override IServiceCollection ConfigureApi(IServiceCollection services)
            {
                var modelBuilder      = new TestModelBuilder();
                var modelMapper       = new TestModelMapper();
                var querySourcer      = new TestQuerySourcer();
                var changeSetPreparer = new TestChangeSetPreparer();
                var submitExecutor    = new TestSubmitExecutor();

                services.CutoffPrevious <IQueryExecutor>(DefaultQueryExecutor.Instance);
                services.CutoffPrevious <IModelBuilder>(modelBuilder);
                services.CutoffPrevious <IModelMapper>(modelMapper);
                services.CutoffPrevious <IQueryExpressionSourcer>(querySourcer);
                services.CutoffPrevious <IChangeSetPreparer>(changeSetPreparer);
                services.CutoffPrevious <ISubmitExecutor>(submitExecutor);

                return(services);
            }
        public void Apply_should_discover_for_multiple_entities()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S", "T", "U")
                  .Association("S", RelationshipMultiplicity.Many, "T", RelationshipMultiplicity.ZeroOrOne)
                  .Association("T", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne)
                  .Association("T", RelationshipMultiplicity.Many, "U", RelationshipMultiplicity.ZeroOrOne)
                  .Association("U", RelationshipMultiplicity.Many, "T", RelationshipMultiplicity.ZeroOrOne)
                  .Association("U", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne)
                  .Association("S", RelationshipMultiplicity.Many, "U", RelationshipMultiplicity.ZeroOrOne);

            (new AssociationInverseDiscoveryConvention()).Apply(model, new DbModel(model, null));

            Assert.Equal(3, model.AssociationTypes.Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
Example #18
0
            protected override IServiceCollection ConfigureApi(IServiceCollection services)
            {
                var modelBuilder = new TestModelBuilder();
                var modelMapper = new TestModelMapper();
                var querySourcer = new TestQuerySourcer();
                var changeSetPreparer = new TestChangeSetPreparer();
                var submitExecutor = new TestSubmitExecutor();

                services.CutoffPrevious<IQueryExecutor>(DefaultQueryExecutor.Instance);
                services.CutoffPrevious<IModelBuilder>(modelBuilder);
                services.CutoffPrevious<IModelMapper>(modelMapper);
                services.CutoffPrevious<IQueryExpressionSourcer>(querySourcer);
                services.CutoffPrevious<IChangeSetPreparer>(changeSetPreparer);
                services.CutoffPrevious<ISubmitExecutor>(submitExecutor);

                return services;
            }
Example #19
0
            protected override IServiceCollection ConfigureApi(IServiceCollection services)
            {
                var modelBuilder      = new TestModelBuilder();
                var modelMapper       = new TestModelMapper();
                var querySourcer      = new TestQuerySourcer();
                var changeSetPreparer = new TestChangeSetInitializer();
                var submitExecutor    = new TestSubmitExecutor();

                services.AddCoreServices(this.GetType());
                services.AddService <IModelBuilder>((sp, next) => modelBuilder);
                services.AddService <IModelMapper>((sp, next) => modelMapper);
                services.AddService <IQueryExpressionSourcer>((sp, next) => querySourcer);
                services.AddService <IChangeSetInitializer>((sp, next) => changeSetPreparer);
                services.AddService <ISubmitExecutor>((sp, next) => submitExecutor);

                return(services);
            }
Example #20
0
        private static void GetGroupByParams(string value, out IQueryable data, out ODataQueryContext context, out ODataQuerySettings settings,
                                             out ApplyGroupbyClause groupByClause, out DefaultAssembliesResolver assembliesResolver,
                                             out GroupByImplementation groupByImplementation, out Type keyType, out IEnumerable <LambdaExpression> propertiesToGroupByExpressions)
        {
            string queryOption = "$apply";

            data     = TestDataSource.CreateData();
            settings = new ODataQuerySettings()
            {
                PageSize = 2000,
                HandleNullPropagation = HandleNullPropagationOption.False
            };
            var _settings = settings;

            var model = TestModelBuilder.CreateModel(new Type[] { typeof(Category), typeof(Product), typeof(Sales) });

            context = new ODataQueryContext(model, typeof(Sales),
                                            new ODataPath(new ODataPathSegment[] { new EntitySetPathSegment("Sales") }));
            var _context = context;

            IEdmNavigationSource source = model.FindDeclaredEntitySet("Sales");
            var parser = new ODataQueryOptionParser(model,
                                                    model.FindDeclaredType("System.Web.OData.Aggregation.Tests.Common.Sales"),
                                                    source,
                                                    new Dictionary <string, string>()
            {
                { queryOption, value }
            });

            var applyCaluse = parser.ParseApply();

            groupByClause      = applyCaluse.Transformations.First().Item2 as ApplyGroupbyClause;
            assembliesResolver = new DefaultAssembliesResolver();
            var _assembliesResolver = assembliesResolver;

            groupByImplementation = new GroupByImplementation()
            {
                Context = context
            };
            keyType = groupByImplementation.GetGroupByKeyType(groupByClause);
            var entityParam = Expression.Parameter(context.ElementClrType, "$it");

            propertiesToGroupByExpressions = groupByClause.SelectedPropertiesExpressions.Select(
                exp =>
                FilterBinder.Bind(exp, _context.ElementClrType, _context.Model, _assembliesResolver, _settings, entityParam));
        }
Example #21
0
            public static new IServiceCollection ConfigureApi(Type apiType, IServiceCollection services)
            {
                var modelBuilder      = new TestModelBuilder();
                var modelMapper       = new TestModelMapper();
                var querySourcer      = new TestQuerySourcer();
                var changeSetPreparer = new TestChangeSetInitializer();
                var submitExecutor    = new TestSubmitExecutor();

                services.AddCoreServices(apiType);
                services.AddService <IModelBuilder>((sp, next) => modelBuilder);
                services.AddService <IModelMapper>((sp, next) => modelMapper);
                services.AddService <IQueryExpressionSourcer>((sp, next) => querySourcer);
                services.AddService <IChangeSetInitializer>((sp, next) => changeSetPreparer);
                services.AddService <ISubmitExecutor>((sp, next) => submitExecutor);

                return(services);
            }
        public void Apply_should_discover_optional_to_collection_association_pair()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                    .Association("T", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.Equal(RelationshipMultiplicity.ZeroOrOne, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.Many, associationType.TargetEnd.RelationshipMultiplicity);
        }
        public void Apply_should_discover_self_referencing_association_pair()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S")
                  .Association("S", RelationshipMultiplicity.ZeroOrOne, "S", RelationshipMultiplicity.Many)
                  .Association("S", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne);

            (new AssociationInverseDiscoveryConvention()).Apply(model, new DbModel(model, null));

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.Equal(RelationshipMultiplicity.ZeroOrOne, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.Many, associationType.TargetEnd.RelationshipMultiplicity);
        }
        public void Apply_should_discover_collection_to_collection_association_pair()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S", "T")
                  .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                  .Association("T", RelationshipMultiplicity.ZeroOrOne, "S", RelationshipMultiplicity.Many);

            ((IEdmConvention) new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.Equal(RelationshipMultiplicity.Many, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.Many, associationType.TargetEnd.RelationshipMultiplicity);
        }
        public void Apply_should_discover_optional_to_optional_association_pair()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("S", EdmAssociationEndKind.Many, "T", EdmAssociationEndKind.Optional)
                    .Association("T", EdmAssociationEndKind.Many, "S", EdmAssociationEndKind.Optional);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(1, model.GetAssociationTypes().Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.GetAssociationTypes().Single();

            Assert.Equal(EdmAssociationEndKind.Optional, associationType.SourceEnd.EndKind);
            Assert.Equal(EdmAssociationEndKind.Optional, associationType.TargetEnd.EndKind);
        }
Example #26
0
        public async Task SetUp()
        {
            string hashedAccountId = null;

            _userRef = Guid.Empty;

            await InitialiseEmployerAccountData(async builder =>
            {
                var data = new TestModelBuilder()
                           .WithNewUser()
                           .WithNewAccount()
                           .WithNewLegalEntity();

                await builder.SetupDataAsync(data);

                hashedAccountId = data.CurrentAccount.AccountOutput.HashedAccountId;
                _userRef        = data.CurrentUser.UserOutput.UserRef;
            });

            WhenControllerActionIsCalled($"https://localhost:44330/api/accounts/{hashedAccountId}/users");
        }
        public void Apply_should_transfer_constraint_and_clr_property_info_annotation()
        {
            EdmModel model
                = new TestModelBuilder()
                  .Entities("S", "T")
                  .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                  .Association("T", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne);

            var association2 = model.AssociationTypes.Last();

            var mockPropertyInfo = new MockPropertyInfo();

            association2.SourceEnd.SetClrPropertyInfo(mockPropertyInfo);

            var referentialConstraint
                = new ReferentialConstraint(
                      association2.SourceEnd,
                      association2.TargetEnd,
                      new[] { new EdmProperty("P") },
                      new[] { new EdmProperty("D") });

            association2.Constraint = referentialConstraint;

            ((IEdmConvention) new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.NotSame(association2, associationType);
            Assert.Same(referentialConstraint, associationType.Constraint);
            Assert.Same(associationType.SourceEnd, referentialConstraint.FromRole);
            Assert.Same(associationType.TargetEnd, referentialConstraint.ToRole);
            Assert.Same(mockPropertyInfo.Object, associationType.TargetEnd.GetClrPropertyInfo());
        }
            public virtual void Can_configure_one_to_one_relationship_from_an_owned_type(TestModelBuilder modelBuilder)
            {
                var model = modelBuilder.Model;

                modelBuilder.Ignore<Customer>();
                modelBuilder.Entity<OtherCustomer>().OwnsOne(c => c.Details)
                    .HasOne<SpecialCustomer>()
                    .WithOne()
                    .HasPrincipalKey<SpecialCustomer>();

                Assert.NotNull(model.FindEntityType(typeof(CustomerDetails)));

                modelBuilder.Entity<SpecialCustomer>().OwnsOne(c => c.Details);

                modelBuilder.Validate();

                var ownership = model.FindEntityType(typeof(OtherCustomer)).FindNavigation(nameof(Customer.Details)).ForeignKey;
                var foreignKey = model.FindEntityType(typeof(SpecialCustomer)).GetReferencingForeignKeys()
                    .Single(fk => fk.DeclaringEntityType.ClrType == typeof(CustomerDetails)
                                  && fk.PrincipalToDependent == null);
                Assert.Same(ownership.DeclaringEntityType, foreignKey.DeclaringEntityType);
                Assert.NotEqual(ownership.Properties.Single().Name, foreignKey.Properties.Single().Name);
                Assert.Equal(2, model.GetEntityTypes().Count(e => e.ClrType == typeof(CustomerDetails)));
                Assert.Equal(2, ownership.DeclaringEntityType.GetForeignKeys().Count());
            }
        public void Apply_should_not_discover_when_too_many_associations()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                    .Association("S", RelationshipMultiplicity.ZeroOrOne, "T", RelationshipMultiplicity.Many)
                    .Association("T", RelationshipMultiplicity.ZeroOrOne, "S", RelationshipMultiplicity.Many);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(3, model.AssociationTypes.Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
        public void Apply_should_discover_for_multiple_entities()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T", "U")
                    .Association("S", EdmAssociationEndKind.Many, "T", EdmAssociationEndKind.Optional)
                    .Association("T", EdmAssociationEndKind.Many, "S", EdmAssociationEndKind.Optional)
                    .Association("T", EdmAssociationEndKind.Many, "U", EdmAssociationEndKind.Optional)
                    .Association("U", EdmAssociationEndKind.Many, "T", EdmAssociationEndKind.Optional)
                    .Association("U", EdmAssociationEndKind.Many, "S", EdmAssociationEndKind.Optional)
                    .Association("S", EdmAssociationEndKind.Many, "U", EdmAssociationEndKind.Optional);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(3, model.GetAssociationTypes().Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
        public void Apply_should_not_discover_when_too_many_associations()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T")
                    .Association("S", EdmAssociationEndKind.Optional, "T", EdmAssociationEndKind.Many)
                    .Association("S", EdmAssociationEndKind.Optional, "T", EdmAssociationEndKind.Many)
                    .Association("T", EdmAssociationEndKind.Optional, "S", EdmAssociationEndKind.Many);

            ((IEdmConvention)new AssociationInverseDiscoveryConvention()).Apply(model);

            Assert.Equal(3, model.GetAssociationTypes().Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
        public void Configure_mapping_can_process_entity_splitting()
        {
            EdmModel model =
                new TestModelBuilder()
                    .Entity("E")
                    .Key("P1")
                    .Property("P2")
                    .Property("P3")
                    .Property("P4")
                    .Property("P5");
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderInfo, ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType = model.GetEntityType("E");
            var modelConfiguration = new ModelConfiguration();
            var entityMappingConfiguration1 =
                new EntityMappingConfiguration
                    {
                        Properties =
                            new List<PropertyPath>
                                {
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P1").GetClrPropertyInfo(
                                            
                                        )),
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P2").GetClrPropertyInfo(
                                            
                                        )),
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P3").GetClrPropertyInfo(
                                            
                                        ))
                                },
                        TableName = new DatabaseName("E1")
                    };
            var entityMappingConfiguration2 =
                new EntityMappingConfiguration
                    {
                        Properties =
                            new List<PropertyPath>
                                {
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P1").GetClrPropertyInfo(
                                            
                                        )),
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P4").GetClrPropertyInfo(
                                            
                                        )),
                                    new PropertyPath(
                                        entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P5").GetClrPropertyInfo(
                                            
                                        ))
                                },
                        TableName = new DatabaseName("E2")
                    };
            var entityConfiguration = modelConfiguration.Entity(entityType.GetClrType());
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration1);
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration2);
            modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest);

            var entityTypeMapping = databaseMapping.GetEntityTypeMapping(entityType);
            var table1 = entityTypeMapping.MappingFragments[0].Table;
            var table2 = entityTypeMapping.MappingFragments[1].Table;
            Assert.NotSame(table1, table2);
            Assert.Equal("E1", table1.GetTableName().Name);
            Assert.Equal("E2", table2.GetTableName().Name);
            Assert.Equal(3, table1.Properties.Count);
            Assert.Equal(3, table2.Properties.Count);
            Assert.Equal(2, entityTypeMapping.MappingFragments.Count);
            var entityTypeMappingFragment1 = entityTypeMapping.MappingFragments[0];
            var entityTypeMappingFragment2 = entityTypeMapping.MappingFragments[1];
            Assert.Equal(3, entityTypeMappingFragment1.ColumnMappings.Count());
            Assert.Equal("P1", entityTypeMappingFragment1.ColumnMappings.ElementAt(0).ColumnProperty.Name);
            Assert.Equal("P2", entityTypeMappingFragment1.ColumnMappings.ElementAt(1).ColumnProperty.Name);
            Assert.Equal("P3", entityTypeMappingFragment1.ColumnMappings.ElementAt(2).ColumnProperty.Name);
            Assert.Equal(3, entityTypeMappingFragment2.ColumnMappings.Count());
            Assert.Equal("P1", entityTypeMappingFragment2.ColumnMappings.ElementAt(0).ColumnProperty.Name);
            Assert.Equal("P4", entityTypeMappingFragment2.ColumnMappings.ElementAt(1).ColumnProperty.Name);
            Assert.Equal("P5", entityTypeMappingFragment2.ColumnMappings.ElementAt(2).ColumnProperty.Name);
        }
        public void Apply_should_discover_for_multiple_entities()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S", "T", "U")
                    .Association("S", RelationshipMultiplicity.Many, "T", RelationshipMultiplicity.ZeroOrOne)
                    .Association("T", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne)
                    .Association("T", RelationshipMultiplicity.Many, "U", RelationshipMultiplicity.ZeroOrOne)
                    .Association("U", RelationshipMultiplicity.Many, "T", RelationshipMultiplicity.ZeroOrOne)
                    .Association("U", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne)
                    .Association("S", RelationshipMultiplicity.Many, "U", RelationshipMultiplicity.ZeroOrOne);

            (new AssociationInverseDiscoveryConvention()).Apply(model, new DbModel(model, null));

            Assert.Equal(3, model.AssociationTypes.Count());
            Assert.Equal(3, model.Containers.Single().AssociationSets.Count());
        }
        public void Apply_should_discover_self_referencing_association_pair()
        {
            EdmModel model
                = new TestModelBuilder()
                    .Entities("S")
                    .Association("S", RelationshipMultiplicity.ZeroOrOne, "S", RelationshipMultiplicity.Many)
                    .Association("S", RelationshipMultiplicity.Many, "S", RelationshipMultiplicity.ZeroOrOne);

            (new AssociationInverseDiscoveryConvention()).Apply(model, new DbModel(model, null));

            Assert.Equal(1, model.AssociationTypes.Count());
            Assert.Equal(1, model.Containers.Single().AssociationSets.Count());

            var associationType = model.AssociationTypes.Single();

            Assert.Equal(RelationshipMultiplicity.ZeroOrOne, associationType.SourceEnd.RelationshipMultiplicity);
            Assert.Equal(RelationshipMultiplicity.Many, associationType.TargetEnd.RelationshipMultiplicity);
        }
        public void TPC_with_IA_on_non_leaf_type_not_allowed()
        {
            new Exception("The association 'Related_to_Base' between entity types 'Related' and 'Base' is invalid. In a TPC hierarchy independent associations are only allowed on the most derived types.")
                .ValidateMessage("EntityMappingConfiguration_TPCWithIAsOnNonLeafType", "Related_to_Base", "Related", "Base");

            var modelBuilder = 
             new TestModelBuilder()
                .Entity("Base")
                .Key("P1")
                .Property("P2")
                .Subclass("Derived");

            modelBuilder.Entity("Related");
            modelBuilder.Association(
                "Related_To_Base", "Related", RelationshipMultiplicity.One, "BaseEntities", 
                "Base", RelationshipMultiplicity.Many, "RelatedEntities");

            EdmModel model = modelBuilder;
            var databaseMapping = 
                new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderInfo, ProviderRegistry.Sql2008_ProviderManifest)
                .Generate(model);

            var modelConfiguration = new ModelConfiguration();
            modelConfiguration.Entity(model.GetEntityType("Derived").GetClrType())
                              .AddMappingConfiguration(
                                  new EntityMappingConfiguration
                                  {
                                      MapInheritedProperties = true,
                                      TableName = new DatabaseName("DerivedEntities")
                                  });

            Assert.Throws<InvalidOperationException>(
                () => modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest))
                .ValidateMessage("EntityMappingConfiguration_TPCWithIAsOnNonLeafType", "Related_To_Base", "Related", "Base");
        }
        public void Configure_entity_splitting_should_throw_if_ignored_property_is_mapped()
        {
            EdmModel model =
                new TestModelBuilder()
                    .Entity("E")
                    .Key("P1");
            var databaseMapping = new DatabaseMappingGenerator(ProviderRegistry.Sql2008_ProviderInfo, ProviderRegistry.Sql2008_ProviderManifest).Generate(model);

            var entityType = model.GetEntityType("E");
            var modelConfiguration = new ModelConfiguration();
            var entityConfiguration = modelConfiguration.Entity(entityType.GetClrType());
            var p1PropertyInfo = entityType.GetDeclaredPrimitiveProperties().SingleOrDefault(p => p.Name == "P1").GetClrPropertyInfo();
            var entityMappingConfiguration1 =
                new EntityMappingConfiguration
                    {
                        Properties = new List<PropertyPath>
                                         {
                                             new PropertyPath(p1PropertyInfo),
                                             new PropertyPath(new MockPropertyInfo(typeof(int), "P2"))
                                         },
                        TableName = new DatabaseName("E")
                    };
            entityConfiguration.AddMappingConfiguration(entityMappingConfiguration1);

            Assert.Equal(
                Strings.EntityMappingConfiguration_CannotMapIgnoredProperty("E", "P2"),
                Assert.Throws<InvalidOperationException>(
                    () => modelConfiguration.Configure(databaseMapping, ProviderRegistry.Sql2008_ProviderManifest)).Message);
        }