Example #1
0
        public void EntityKeyConvention_DoesnotFigureOutKeyPropertyOnDerivedTypes()
        {
            MockType baseType =
                new MockType("BaseType")
                .Property <uint>("ID");

            MockType derivedType =
                new MockType("DerivedType")
                .Property <int>("DerivedTypeID")
                .BaseType(baseType);

            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.AddEntityType(derivedType).DerivesFrom(builder.AddEntityType(baseType));

            IEdmModel model = builder.GetEdmModel();

            IEdmEntityType baseEntity = model.AssertHasEntityType(baseType);

            baseEntity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int64);

            IEdmEntityType derivedEntity = model.AssertHasEntityType(derivedType);

            derivedEntity.AssertHasPrimitiveProperty(model, "DerivedTypeID", EdmPrimitiveTypeKind.Int32, isNullable: false);
        }
Example #2
0
        public void ModelBuilder_BindsToTheClosestEntitySet_ForNavigationProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <CarManufacturer>("car_manufacturers");
            builder.EntitySet <MotorcycleManufacturer>("motorcycle_manufacturers");

            IEdmModel model = builder.GetEdmModel();

            model.AssertHasEntitySet("vehicles", typeof(Vehicle));
            IEdmEntitySet vehicles = model.EntityContainers().Single().FindEntitySet("vehicles");

            IEdmEntityType car        = model.AssertHasEntityType(typeof(Car));
            IEdmEntityType motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            IEdmEntityType sportbike  = model.AssertHasEntityType(typeof(SportBike));

            Assert.Equal(2, vehicles.NavigationTargets.Count());
            vehicles.AssertHasNavigationTarget(
                car.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "car_manufacturers");
            vehicles.AssertHasNavigationTarget(
                motorcycle.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "motorcycle_manufacturers");
            vehicles.AssertHasNavigationTarget(
                sportbike.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne),
                "motorcycle_manufacturers");
        }
Example #3
0
        public void ModelBuilder_Ignores_IgnoredTypeAndTheirDerivedTypes()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("Vehicles");
            builder.Ignore <Motorcycle>();

            IEdmModel model = builder.GetEdmModel();

            // ignore motorcycle, sportbike and MotorcycleManufacturer
            Assert.Equal(_totalExpectedSchemaTypesForVehiclesModel - 3, model.SchemaElements.Count());
            Assert.Equal(1, model.EntityContainers().Single().EntitySets().Count());
            model.AssertHasEntitySet("Vehicles", typeof(Vehicle));

            var vehicle = model.AssertHasEntityType(typeof(Vehicle));

            Assert.Equal(2, vehicle.Key().Count());
            Assert.Equal(3, vehicle.Properties().Count());
            vehicle.AssertHasKey(model, "Model", EdmPrimitiveTypeKind.Int32);
            vehicle.AssertHasKey(model, "Name", EdmPrimitiveTypeKind.String);
            vehicle.AssertHasPrimitiveProperty(model, "WheelCount", EdmPrimitiveTypeKind.Int32, isNullable: false);

            var car = model.AssertHasEntityType(typeof(Car));

            Assert.Equal(vehicle, car.BaseEntityType());
            Assert.Equal(2, car.Key().Count());
            Assert.Equal(5, car.Properties().Count());
            car.AssertHasPrimitiveProperty(model, "SeatingCapacity", EdmPrimitiveTypeKind.Int32, isNullable: false);
            car.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);
        }
Example #4
0
        public void CanCreateDerivedTypesInAnyOrder()
        {
            var builder = new ODataModelBuilder();

            builder
            .Entity <SportBike>()
            .DerivesFrom <Motorcycle>();

            builder
            .Entity <Car>()
            .DerivesFrom <Vehicle>();

            builder
            .Entity <Vehicle>();

            builder
            .Entity <Motorcycle>()
            .DerivesFrom <Vehicle>();

            IEdmModel model = builder.GetEdmModel();

            model.AssertHasEntityType(typeof(Vehicle));
            model.AssertHasEntityType(typeof(Car), typeof(Vehicle));
            model.AssertHasEntityType(typeof(Motorcycle), typeof(Vehicle));
            model.AssertHasEntityType(typeof(SportBike), typeof(Motorcycle));
        }
Example #5
0
        public void CanConfigureBindingPath_NavigationProperties_WithDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            var bindingConfiguration = builder
                                       .EntitySet <BindingCustomer>("Customers")
                                       .Binding
                                       .HasSinglePath((BindingVipCustomer v) => v.VipLocation);

            bindingConfiguration.HasOptionalBinding((BindingUsAddress u) => u.UsCity, "Cities_A");
            bindingConfiguration.HasManyBinding((BindingUsAddress u) => u.UsCities, "Cities_B");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var customers = model.EntityContainer.FindEntitySet("Customers");

            Assert.NotNull(customers);

            // "BindingVipCustomer" entity type
            var vipCustomer = model.AssertHasEntityType(typeof(BindingVipCustomer), typeof(BindingCustomer));

            Assert.Empty(vipCustomer.NavigationProperties());
            IEdmProperty vipLocationProperty = Assert.Single(vipCustomer.Properties());

            Assert.Equal("VipLocation", vipLocationProperty.Name);
            Assert.Equal(EdmPropertyKind.Structural, vipLocationProperty.PropertyKind);
            Assert.False(vipLocationProperty.Type.IsCollection());

            // "BindingUsAddress" complex type
            var usAddress    = model.AssertHasComplexType(typeof(BindingUsAddress), typeof(BindingAddress));
            var cityProperty = usAddress.AssertHasNavigationProperty(model, "UsCity", typeof(BindingCity), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);
            var bindings     = customers.FindNavigationPropertyBindings(cityProperty);
            IEdmNavigationPropertyBinding binding = Assert.Single(bindings);

            Assert.Equal("UsCity", binding.NavigationProperty.Name);
            Assert.Equal("Cities_A", binding.Target.Name);
            Assert.Equal("Microsoft.AspNet.OData.Test.Formatter.BindingVipCustomer/VipLocation/Microsoft.AspNet.OData.Test.Formatter.BindingUsAddress/UsCity", binding.Path.Path);

            IEdmNavigationSource navSource = customers.FindNavigationTarget(cityProperty, binding.Path);

            Assert.Same(navSource, binding.Target);

            var citiesProperty = usAddress.AssertHasNavigationProperty(model, "UsCities", typeof(BindingCity), isNullable: true, multiplicity: EdmMultiplicity.Many);

            bindings = customers.FindNavigationPropertyBindings(citiesProperty);
            binding  = Assert.Single(bindings);
            Assert.Equal("UsCities", binding.NavigationProperty.Name);
            Assert.Equal("Cities_B", binding.Target.Name);
            Assert.Equal("Microsoft.AspNet.OData.Test.Formatter.BindingVipCustomer/VipLocation/Microsoft.AspNet.OData.Test.Formatter.BindingUsAddress/UsCities", binding.Path.Path);

            navSource = customers.FindNavigationTarget(citiesProperty, binding.Path);
            Assert.Same(navSource, binding.Target);

            // "BindingCity" entity type
            model.AssertHasEntityType(typeof(BindingCity));
        }
Example #6
0
        public void ModelBuilder_Doesnot_Override_AbstractnessOfEntityTypes_IfSet()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.Entity <Vehicle>();
            builder.Entity <Motorcycle>().Abstract();

            IEdmModel model = builder.GetEdmModel();

            Assert.Equal(_totalExpectedSchemaTypesForVehiclesModel, model.SchemaElements.Count());
            Assert.True(model.AssertHasEntityType(typeof(Motorcycle)).IsAbstract);
            Assert.False(model.AssertHasEntityType(typeof(SportBike)).IsAbstract);
        }
Example #7
0
        public void ModelBuilder_CanHaveAnAbstractDerivedTypeOfConcreteBaseType()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.Entity <Vehicle>();
            builder.Entity <SportBike>().Abstract();

            IEdmModel model = builder.GetEdmModel();

            Assert.Equal(_totalExpectedSchemaTypesForVehiclesModel, model.SchemaElements.Count());
            Assert.False(model.AssertHasEntityType(typeof(Motorcycle)).IsAbstract);
            Assert.True(model.AssertHasEntityType(typeof(SportBike)).IsAbstract);

            Assert.Equal(model.AssertHasEntityType(typeof(SportBike)).BaseEntityType(), model.AssertHasEntityType(typeof(Motorcycle)));
        }
Example #8
0
        public void CanConfigureSingleProperty_MultipleBindingPath_For_NavigationProperties_WithComplex_Multiple()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            builder
            .EntitySet <BindingCustomer>("Customers")
            .Binding
            .HasSinglePath(c => c.Location)
            .HasRequiredBinding(a => a.City, "Cities_A");

            builder
            .EntitySet <BindingCustomer>("Customers")
            .Binding
            .HasSinglePath(c => c.Address)
            .HasRequiredBinding(a => a.City, "Cities_B");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var customers = model.EntityContainer.FindEntitySet("Customers");

            Assert.NotNull(customers);

            // "BindingCustomer" entity type
            var customer = model.AssertHasEntityType(typeof(BindingCustomer));

            Assert.Empty(customer.NavigationProperties());

            // "BindingAddress" complex type
            var address      = model.AssertHasComplexType(typeof(BindingAddress));
            var cityProperty = address.AssertHasNavigationProperty(model, "City", typeof(BindingCity), isNullable: false, multiplicity: EdmMultiplicity.One);
            var bindings     = customers.FindNavigationPropertyBindings(cityProperty).ToList();

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

            Assert.Equal("City, City", String.Join(", ", bindings.Select(e => e.NavigationProperty.Name)));

            Assert.NotNull(bindings.SingleOrDefault(c => c.Target.Name == "Cities_A"));
            Assert.NotNull(bindings.SingleOrDefault(c => c.Target.Name == "Cities_B"));

            Assert.NotNull(bindings.SingleOrDefault(c => c.Path.Path == "Location/City"));
            Assert.NotNull(bindings.SingleOrDefault(c => c.Path.Path == "Address/City"));

            // "BindingCity" entity type
            model.AssertHasEntityType(typeof(BindingCity));
        }
        public void SelfLinksGenerationConvention_Uses_GetByIdWithoutCast_IfDerivedTypeDoesnotHaveNavigationProperty()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var motorcycles = builder.EntitySet <Motorcycle>("motorcycles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType sportbikeType        = model.AssertHasEntityType(typeof(SportBike));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{controller}({id})");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Uri uri = linkBuilder.BuildEditLink(
                new EntityInstanceContext(model, vehiclesEdmEntitySet, sportbikeType, request.GetUrlHelper(), new SportBike {
                Model = 2009, Name = "Ninja"
            }));

            Assert.Equal("http://localhost/motorcycles(Model=2009,Name='Ninja')", uri.AbsoluteUri);
        }
        public void SelfLinksGenerationConvention_Uses_GetByIdWithCast_IfDerivedTypeHasNavigationProperty()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var vehicles = builder.EntitySet <Vehicle>("vehicles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType carType = model.AssertHasEntityType(typeof(Car));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetByIdWithCast, "{controller}({id})/{entitytype}");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Uri uri = linkBuilder.BuildEditLink(
                new EntityInstanceContext(model, vehiclesEdmEntitySet, carType, request.GetUrlHelper(), new Car {
                Model = 2009, Name = "Accord"
            }));

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car", uri.AbsoluteUri);
        }
        public void DataMemberAttributeEdmPropertyConvention_PropertyAliased_IfEnabled(string propertyAlias, bool modelAliasing)
        {
            // Arrange
            MockType relatedType =
                new MockType("RelatedEntity")
                .Property <int>("ID");
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(relatedType, "RelatedEntity", new DataMemberAttribute {
                Name = "AliasRelatedEntity"
            });

            type.Setup(t => t.GetCustomAttributes(It.IsAny <Type>(), It.IsAny <bool>()))
            .Returns(new[] { new DataContractAttribute() });

            // Act
            ODataConventionModelBuilder builder = ODataConventionModelBuilderHelper.CreateWithModelAliasing(modelAliasing);

            builder.AddEntityType(type);
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType entity = model.AssertHasEntityType(type);

            entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32);
            entity.AssertHasNavigationProperty(
                model,
                propertyAlias,
                relatedType,
                isNullable: true,
                multiplicity: EdmMultiplicity.ZeroOrOne);
        }
Example #12
0
        public void CreateEdmModel_WithSingleton_CanAddNavigationLinkToDerivedNavigationProperty()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            var vehicle      = builder.AddEntityType(typeof(Vehicle));
            var car          = builder.AddEntityType(typeof(Car)).DerivesFrom(vehicle);
            var manufacturer = builder.AddEntityType(typeof(CarManufacturer));
            var fordo        = builder.AddSingleton("Fordo", manufacturer);
            var navProperty  = car.AddNavigationProperty(typeof(Car).GetProperty("Manufacturer"), EdmMultiplicity.One);

            var contoso = builder.AddSingleton("Contoso", vehicle);
            var binding = contoso.AddBinding(navProperty, fordo);

            contoso.HasNavigationPropertyLink(navProperty, new NavigationLinkBuilder((ctxt, property) => new Uri("http://works/"), followsConventions: false));

            // Act & assert
            IEdmModel model             = builder.GetEdmModel();
            var       motorcycleEdmType = model.AssertHasEntityType(typeof(Car));
            var       edmNavProperty    = motorcycleEdmType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: false, multiplicity: EdmMultiplicity.One);
            var       edmContoso        = model.EntityContainer.FindSingleton("Contoso");

            Assert.NotNull(model.GetNavigationSourceLinkBuilder(edmContoso));
            Assert.Equal(
                "http://works/",
                model.GetNavigationSourceLinkBuilder(edmContoso).BuildNavigationLink(new ResourceContext(), edmNavProperty, ODataMetadataLevel.MinimalMetadata).AbsoluteUri);
        }
        public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet = model.EntityContainer.FindEntitySet("vehicles");
            IEdmEntityType         carType = model.AssertHasEntityType(typeof(Car));
            IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            HttpConfiguration configuration = new HttpConfiguration();
            string            routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.SetConfiguration(configuration);
            request.ODataProperties().RouteName = routeName;

            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);

            var serializerContext = new ODataSerializerContext {
                Model = model, NavigationSource = vehiclesEdmEntitySet, Url = request.GetUrlHelper()
            };
            var entityContext = new EntityInstanceContext(serializerContext, carType.AsReference(), new Car {
                Model = 2009, Name = "Accord"
            });

            Uri uri = linkBuilder.BuildNavigationLink(entityContext, carManufacturerProperty, ODataMetadataLevel.FullMetadata);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/System.Web.OData.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
        }
        public void GetEdmModel_CanSetDependentPropertyNullable_ForOptionalNavigation()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <User> userType = builder.EntityType <User>();

            userType.HasKey(c => c.UserId).HasMany(c => c.Roles);
            userType.Property(u => u.StringPrincipal);

            EntityTypeConfiguration <Role> roleType = builder.EntityType <Role>();

            roleType.HasKey(r => r.RoleId)
            .HasOptional(r => r.User, (r, u) => r.UserStringForeignKey == u.StringPrincipal);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            Assert.NotNull(model);
            IEdmEntityType roleEntityType = model.AssertHasEntityType(typeof(Role));

            roleEntityType.AssertHasNavigationProperty(model, "User", typeof(User), isNullable: true,
                                                       multiplicity: EdmMultiplicity.ZeroOrOne);

            IEdmProperty edmProperty = Assert.Single(roleEntityType.Properties().Where(c => c.Name == "UserStringForeignKey"));

            Assert.True(edmProperty.Type.IsNullable);
        }
        public void GetEdmModel_PropertyWithETag_IsConcurrencyToken()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            builder.EntitySet <Customer>("Customers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType         type     = model.AssertHasEntityType(typeof(Customer));
            IEdmStructuralProperty property =
                type.AssertHasPrimitiveProperty(model, "Name", EdmPrimitiveTypeKind.String, isNullable: true);

            IEdmEntitySet customers = model.EntityContainer.FindEntitySet("Customers");

            Assert.NotNull(customers);

            IEnumerable <IEdmStructuralProperty> currencyProperties = model.GetConcurrencyProperties(customers);
            IEdmStructuralProperty currencyProperty = Assert.Single(currencyProperties);

            Assert.Same(property, currencyProperty);
        }
        public void SelfLinksGenerationConvention_Throws_If_RouteInCorrect()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var motorcycles = builder.EntitySet <Motorcycle>("motorcycles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainers().Single().EntitySets().Single();
            IEdmEntityType sportbikeType        = model.AssertHasEntityType(typeof(SportBike));

            HttpConfiguration configuration = new HttpConfiguration();

            configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{Cntroller}({id})");

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost");

            request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration;
            request.Properties[HttpPropertyKeys.HttpRouteDataKey]     = new HttpRouteData(new HttpRoute());

            IEntitySetLinkBuilder linkBuilder = model.GetEntitySetLinkBuilder(vehiclesEdmEntitySet);

            Assert.Throws <InvalidOperationException>(
                () => linkBuilder.BuildEditLink(new EntityInstanceContext(model, vehiclesEdmEntitySet, sportbikeType, request.GetUrlHelper(), new SportBike {
                Model = 2009, Name = "Ninja"
            })),
                "EditLink generation failed. Check that you have the 'OData.GetById' route correctly registered.");
        }
Example #17
0
        public void CannotBindNavigationPropertyAutmatically_WhenMultipleEntitySetsOfPropertyType_Exist()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            builder.EntitySet <Motorcycle>("motorcycles1").HasRequiredBinding(m => m.Manufacturer, "NorthWestMotorcycleManufacturers");
            builder.EntitySet <Motorcycle>("motorcycles2");
            builder.EntitySet <MotorcycleManufacturer>("NorthWestMotorcycleManufacturers");
            builder.EntitySet <MotorcycleManufacturer>("SouthWestMotorcycleManufacturers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntitySet motorcycles1 = model.EntityContainer.FindEntitySet("motorcycles1");

            Assert.NotNull(motorcycles1);

            var motorcycle      = model.AssertHasEntityType(typeof(Motorcycle));
            var manufacturerNav = motorcycle.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.One);
            var bindings        = motorcycles1.FindNavigationPropertyBindings(manufacturerNav);
            IEdmNavigationPropertyBinding binding = Assert.Single(bindings);

            Assert.Equal("Manufacturer", binding.NavigationProperty.Name);
            Assert.Equal("NorthWestMotorcycleManufacturers", binding.Target.Name);
            Assert.Equal("Manufacturer", binding.Path.Path);

            IEdmEntitySet motorcycles2 = model.EntityContainer.FindEntitySet("motorcycles2");

            Assert.Null(motorcycles2.FindNavigationPropertyBindings(manufacturerNav));
        }
Example #18
0
        public void CanConfigureManyBinding_For_NavigationPropertiesInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            builder
            .EntitySet <Vehicle>("vehicles")
            .HasManyBinding((Motorcycle m) => m.Manufacturers, "manufacturers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var vehicles = model.EntityContainer.FindEntitySet("vehicles");

            Assert.NotNull(vehicles);

            var motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var motorcycleManufacturerProperty = motorcycle.AssertHasNavigationProperty(model, "Manufacturers", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.Many);

            var motorcycleManufacturerPropertyTargetSet = vehicles.FindNavigationTarget(motorcycleManufacturerProperty);

            Assert.NotNull(motorcycleManufacturerPropertyTargetSet);
            Assert.Equal("manufacturers", motorcycleManufacturerPropertyTargetSet.Name);

            IEdmNavigationPropertyBinding binding = Assert.Single(vehicles.FindNavigationPropertyBindings(motorcycleManufacturerProperty));

            Assert.Same(motorcycleManufacturerPropertyTargetSet, binding.Target);
            Assert.Equal("Microsoft.AspNet.OData.Test.Builder.TestModels.Motorcycle/Manufacturers", binding.Path.Path);
        }
        public void SelfLinksGenerationConvention_Uses_GetByIdWithoutCast_IfDerivedTypeDoesnotHaveNavigationProperty()
        {
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();
            var motorcycles = builder.EntitySet <Motorcycle>("motorcycles");

            IEdmModel      model = builder.GetEdmModel();
            IEdmEntitySet  vehiclesEdmEntitySet = model.EntityContainer.EntitySets().Single();
            IEdmEntityType sportbikeType        = model.AssertHasEntityType(typeof(SportBike));

            var request = RequestFactory.CreateFromModel(model);
            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);
            var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request);
            var entityContext     = new ResourceContext(serializerContext, sportbikeType.AsReference(), new SportBike {
                Model = 2009, Name = "Ninja"
            });

            EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata);

            // This test sometimes writes one of these two:
            //Assert.Equal("http://localhost/motorcycles(Model=2009,Name='Ninja')", );
            //Assert.Equal("http://localhost/motorcycles(Name='Ninja',Model=2009)", );
            var link = selfLinks.IdLink.ToString();

            Assert.Contains("http://localhost/motorcycles", link);
            Assert.Contains("Model=2009", link);
            Assert.Contains("Name='Ninja'", link);
        }
        public void SelfLinksGenerationConvention_Uses_WithoutCast_IfDerivedTypeDoesnotHaveNavigationProperty_ForSingleton()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var myMotorcycle = builder.Singleton <Motorcycle>("MyMotor");

            IEdmModel      model = builder.GetEdmModel();
            IEdmSingleton  vehicleEdmSingleton = model.EntityContainer.FindSingleton("MyMotor");
            IEdmEntityType sportbikeType       = model.AssertHasEntityType(typeof(SportBike));

            HttpRequestMessage request = GetODataRequest(model);
            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehicleEdmSingleton);
            var serializerContext = new ODataSerializerContext {
                Model = model, NavigationSource = vehicleEdmSingleton, Url = request.GetUrlHelper()
            };
            var entityContext = new EntityInstanceContext(serializerContext, sportbikeType.AsReference(), new SportBike {
                Model = 2014, Name = "Ninja"
            });

            // Act
            EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata);

            // Assert
            Assert.Equal("http://localhost/MyMotor", selfLinks.IdLink.ToString());
        }
        public void GetEdmModel_CanSetReferentialConstraint_WithCustomPrincipal()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <User> userType = builder.EntityType <User>();

            userType.HasKey(c => c.UserId).HasMany(c => c.Roles);

            EntityTypeConfiguration <Role> roleType = builder.EntityType <Role>();

            roleType.HasKey(r => r.RoleId)
            .HasRequired(r => r.User, (r, u) => r.UserForeignKey == u.NotKeyPrincipal)
            .CascadeOnDelete(false);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            Assert.NotNull(model);
            IEdmEntityType roleEntityType = model.AssertHasEntityType(typeof(Role));

            IEdmNavigationProperty usersNav = roleEntityType.AssertHasNavigationProperty(model, "User",
                                                                                         typeof(User), isNullable: false, multiplicity: EdmMultiplicity.One);

            Assert.Equal(EdmOnDeleteAction.None, usersNav.OnDelete);

            IEdmStructuralProperty dependentProperty = Assert.Single(usersNav.DependentProperties());

            Assert.Equal("UserForeignKey", dependentProperty.Name);

            IEdmStructuralProperty principalProperty = Assert.Single(usersNav.PrincipalProperties());

            Assert.Equal("NotKeyPrincipal", principalProperty.Name);
        }
        public void SelfLinksGenerationConvention_Uses_WithCast_IfDerivedTypeHasNavigationProperty_ForSingleton()
        {
            // Arrange
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var myVehicle = builder.Singleton <Vehicle>("MyVehicle");

            IEdmModel      model = builder.GetEdmModel();
            IEdmSingleton  vehicleEdmSingleton = model.EntityContainer.FindSingleton("MyVehicle");
            IEdmEntityType carType             = model.AssertHasEntityType(typeof(Car));

            HttpRequestMessage request = GetODataRequest(model);
            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehicleEdmSingleton);
            var serializerContext = new ODataSerializerContext {
                Model = model, NavigationSource = vehicleEdmSingleton, Url = request.GetUrlHelper()
            };
            var entityContext = new EntityInstanceContext(serializerContext, carType.AsReference(), new Car {
                Model = 2014, Name = "Contoso"
            });

            // Act
            EntitySelfLinks selfLinks = linkBuilder.BuildEntitySelfLinks(entityContext, ODataMetadataLevel.FullMetadata);

            // Assert
            Assert.Equal("http://localhost/MyVehicle", selfLinks.IdLink.ToString());
            Assert.Equal("http://localhost/MyVehicle/System.Web.OData.Builder.TestModels.Car", selfLinks.EditLink.ToString());
        }
Example #23
0
        public void CanConfigureManyBinding_For_NavigationPropertiesInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder
            .EntitySet <Vehicle>("vehicles")
            .HasManyBinding((Motorcycle m) => m.Manufacturers, "manufacturers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var vehicles = model.EntityContainers().Single().FindEntitySet("vehicles");

            Assert.NotNull(vehicles);

            var motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var motorcycleManufacturerProperty = motorcycle.AssertHasNavigationProperty(model, "Manufacturers", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.Many);

            var motorcycleManufacturerPropertyTargetSet = vehicles.FindNavigationTarget(motorcycleManufacturerProperty);

            Assert.NotNull(motorcycleManufacturerPropertyTargetSet);
            Assert.Equal("manufacturers", motorcycleManufacturerPropertyTargetSet.Name);
        }
Example #24
0
        public void CanConfigureLinks_For_NavigationPropertiesInDerivedType()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            var vehiclesSet = builder.EntitySet <Vehicle>("vehicles");

            vehiclesSet.HasNavigationPropertyLink(
                vehiclesSet.HasOptionalBinding((Motorcycle m) => m.Manufacturer, "manufacturers").NavigationProperty,
                (ctxt, property) =>
                new Uri(String.Format("http://localhost/vehicles/{0}/{1}/{2}",
                                      ctxt.GetPropertyValue("Model"), ctxt.GetPropertyValue("Name"), property.Name)), followsConventions: false);

            IEdmModel model      = builder.GetEdmModel();
            var       vehicles   = model.EntityContainers().Single().FindEntitySet("vehicles");
            var       motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var       motorcycleManufacturerProperty =
                motorcycle.AssertHasNavigationProperty(
                    model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var serializerContext = new ODataSerializerContext {
                Model = model, EntitySet = vehicles
            };
            var entityContext = new EntityInstanceContext(serializerContext, motorcycle.AsReference(), new Motorcycle {
                Name = "Motorcycle1", Model = 2009
            });

            Uri link = model.GetEntitySetLinkBuilder(vehicles).BuildNavigationLink(entityContext, motorcycleManufacturerProperty, ODataMetadataLevel.Default);

            Assert.Equal("http://localhost/vehicles/2009/Motorcycle1/Manufacturer", link.AbsoluteUri);
        }
Example #25
0
        public void CreateEdmModel_WithSingleton_CanAddBindingToDerivedNavigationProperty()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            var vehicle      = builder.AddEntityType(typeof(Vehicle));
            var motorcycle   = builder.AddEntityType(typeof(Motorcycle)).DerivesFrom(vehicle);
            var manufacturer = builder.AddEntityType(typeof(MotorcycleManufacturer));
            var yamaha       = builder.AddSingleton("Yamaha", manufacturer);
            var navProperty  = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.One);

            var r7 = builder.AddSingleton("Yamaha-R7", motorcycle);

            r7.AddBinding(navProperty, yamaha);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var motorcycleEdmType = model.AssertHasEntityType(typeof(Motorcycle));
            var edmNavProperty    = motorcycleEdmType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.One);

            Assert.Equal(
                "Yamaha",
                model.EntityContainer.FindSingleton("Yamaha-R7").FindNavigationTarget(edmNavProperty).Name);
        }
Example #26
0
        public void CanAddNavigationLink_For_DerivedNavigationProperty()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            var vehicle       = builder.AddEntity(typeof(Vehicle));
            var motorcycle    = builder.AddEntity(typeof(Motorcycle)).DerivesFrom(vehicle);
            var manufacturer  = builder.AddEntity(typeof(MotorcycleManufacturer));
            var manufacturers = builder.AddEntitySet("manufacturers", manufacturer);
            var navProperty   = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.One);

            var vehicles = builder.AddEntitySet("vehicles", vehicle);
            var binding  = vehicles.AddBinding(navProperty, manufacturers);

            vehicles.HasNavigationPropertyLink(navProperty, new NavigationLinkBuilder((ctxt, property) => new Uri("http://works/"), followsConventions: false));

            IEdmModel model             = builder.GetEdmModel();
            var       motorcycleEdmType = model.AssertHasEntityType(typeof(Motorcycle));
            var       edmNavProperty    = motorcycleEdmType.AssertHasNavigationProperty(model, "Manufacturer", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.One);
            var       vehiclesEdmSet    = model.EntityContainers().Single().FindEntitySet("vehicles");

            Assert.NotNull(model.GetEntitySetLinkBuilder(vehiclesEdmSet));
            Assert.Equal(
                "http://works/",
                model.GetEntitySetLinkBuilder(vehiclesEdmSet).BuildNavigationLink(new EntityInstanceContext(), edmNavProperty, ODataMetadataLevel.Default).AbsoluteUri);
        }
Example #27
0
        public void SingletonCanConfigureManyBinding_For_NavigationPropertiesInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            builder
            .Singleton <Vehicle>("MyVehicle")
            .HasManyBinding((Motorcycle m) => m.Manufacturers, "manufacturers");

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            var myVehicle = model.EntityContainer.FindSingleton("MyVehicle");

            Assert.NotNull(myVehicle);

            var motorcycle = model.AssertHasEntityType(typeof(Motorcycle));
            var motorcycleManufacturerProperty = motorcycle.AssertHasNavigationProperty(model, "Manufacturers", typeof(MotorcycleManufacturer), isNullable: false, multiplicity: EdmMultiplicity.Many);

            var motorcycleManufacturerPropertyTarget = myVehicle.FindNavigationTarget(motorcycleManufacturerProperty);

            Assert.NotNull(motorcycleManufacturerPropertyTarget);
            Assert.Equal("manufacturers", motorcycleManufacturerPropertyTarget.Name);
        }
Example #28
0
        public void NavigationLinksGenerationConvention_GeneratesLinksWithCast_ForDerivedProperties()
        {
            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <Vehicle>("vehicles");
            builder.EntitySet <Manufacturer>("manufacturers");

            IEdmModel              model = builder.GetEdmModel();
            IEdmEntitySet          vehiclesEdmEntitySet = model.EntityContainer.FindEntitySet("vehicles");
            IEdmEntityType         carType = model.AssertHasEntityType(typeof(Car));
            IEdmNavigationProperty carManufacturerProperty = carType.AssertHasNavigationProperty(model, "Manufacturer", typeof(CarManufacturer), isNullable: true, multiplicity: EdmMultiplicity.ZeroOrOne);

            var    configuration = RoutingConfigurationFactory.Create();
            string routeName     = "Route";

            configuration.MapODataServiceRoute(routeName, null, model);

            var request = RequestFactory.Create(HttpMethod.Get, "http://localhost", configuration, routeName);

            NavigationSourceLinkBuilderAnnotation linkBuilder = model.GetNavigationSourceLinkBuilder(vehiclesEdmEntitySet);

            linkBuilder.AddNavigationPropertyLinkBuilder(carManufacturerProperty, new NavigationLinkBuilder((context, property) => context.GenerateNavigationPropertyLink(property, includeCast: true), false));
            var serializerContext = ODataSerializerContextFactory.Create(model, vehiclesEdmEntitySet, request);
            var entityContext     = new ResourceContext(serializerContext, carType.AsReference(), new Car {
                Model = 2009, Name = "Accord"
            });

            Uri uri = linkBuilder.BuildNavigationLink(entityContext, carManufacturerProperty, ODataMetadataLevel.MinimalMetadata);

            Assert.Equal("http://localhost/vehicles(Model=2009,Name='Accord')/Microsoft.AspNet.OData.Test.Builder.TestModels.Car/Manufacturer", uri.AbsoluteUri);
        }
Example #29
0
        public void EntityKeyConvention_FiguresOutTheEnumKeyProperty()
        {
            // Arrange
            MockType baseType =
                new MockType("BaseType")
                .Property <Color>("ID");

            ODataConventionModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.AddEntityType(baseType);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType entity = model.AssertHasEntityType(baseType);

            IEdmStructuralProperty enumProperty = entity.AssertHasProperty <IEdmStructuralProperty>(model, "ID", typeof(Color), false);
            IEdmProperty           enumKey      = Assert.Single(entity.DeclaredKey);

            Assert.Same(enumProperty, enumKey);

            Assert.Equal(EdmTypeKind.Enum, enumKey.Type.TypeKind());
            Assert.Equal("Microsoft.AspNet.OData.Test.Builder.TestModels.Color", enumKey.Type.Definition.FullTypeName());
        }
        public void ConcurrencyCheckAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration()
        {
            // Arrange
            MockType type =
                new MockType("Entity")
                .Property(typeof(int), "ID")
                .Property(typeof(int), "Count", new ConcurrencyCheckAttribute());

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var entityType = builder.AddEntityType(type);

            entityType.AddProperty(type.GetProperty("Count")).IsOptional();
            builder.AddEntitySet("EntitySet", entityType);

            // Act
            IEdmModel model = builder.GetEdmModel();

            // Assert
            IEdmEntityType         entity   = model.AssertHasEntityType(type);
            IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty(
                model,
                "Count",
                EdmPrimitiveTypeKind.Int32,
                isNullable: true);

            IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet("EntitySet");

            Assert.NotNull(entitySet);

            IEnumerable <IEdmStructuralProperty> currencyProperties = model.GetConcurrencyProperties(entitySet);
            IEdmStructuralProperty currencyProperty = Assert.Single(currencyProperties);

            Assert.Same(property, currencyProperty);
        }