public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType = builder.EntityType<DCustomer>().HasKey(c => c.Id);
            customerType.Property(c => c.DateTime);
            customerType.Property(c => c.Offset);
            customerType.Property(c => c.Date);
            customerType.Property(c => c.TimeOfDay);

            customerType.Property(c => c.NullableDateTime);
            customerType.Property(c => c.NullableOffset);
            customerType.Property(c => c.NullableDate);
            customerType.Property(c => c.NullableTimeOfDay);

            customerType.CollectionProperty(c => c.DateTimes);
            customerType.CollectionProperty(c => c.Offsets);
            customerType.CollectionProperty(c => c.Dates);
            customerType.CollectionProperty(c => c.TimeOfDays);

            customerType.CollectionProperty(c => c.NullableDateTimes);
            customerType.CollectionProperty(c => c.NullableOffsets);
            customerType.CollectionProperty(c => c.NullableDates);
            customerType.CollectionProperty(c => c.NullableTimeOfDays);

            var customers = builder.EntitySet<DCustomer>("DCustomers");
            customers.HasIdLink(link, true);
            customers.HasEditLink(link, true);

            BuildFunctions(builder);
            BuildActions(builder);

            return builder.GetEdmModel();
        }
示例#2
0
        public static IEdmModel GetExplicitModel(string singletonName)
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            // Define EntityType of Partner
            var partner = builder.EntityType<Partner>();
            partner.HasKey(p => p.ID);
            partner.Property(p => p.Name);
            var partnerCompany = partner.HasRequired(p => p.Company);

            // Define Enum Type
            var category = builder.EnumType<CompanyCategory>();
            category.Member(CompanyCategory.IT);
            category.Member(CompanyCategory.Communication);
            category.Member(CompanyCategory.Electronics);
            category.Member(CompanyCategory.Others);

            // Define EntityType of Company
            var company = builder.EntityType<Company>();
            company.HasKey(p => p.ID);
            company.Property(p => p.Name);
            company.Property(p => p.Revenue);
            company.EnumProperty(p => p.Category);
            var companyPartners = company.HasMany(p => p.Partners);
            companyPartners.IsNotCountable();

            var companyBranches = company.CollectionProperty(p => p.Branches);

            // Define Complex Type: Office
            var office = builder.ComplexType<Office>();
            office.Property(p => p.City);
            office.Property(p => p.Address);

            // Define Derived Type: SubCompany
            var subCompany = builder.EntityType<SubCompany>();
            subCompany.DerivesFrom<Company>();
            subCompany.Property(p => p.Location);
            subCompany.Property(p => p.Description);
            subCompany.ComplexProperty(p => p.Office);

            builder.Namespace = typeof(Partner).Namespace;

            // Define PartnerSet and Company(singleton)
            EntitySetConfiguration<Partner> partnersConfiguration = builder.EntitySet<Partner>("Partners");
            partnersConfiguration.HasIdLink(c=>c.GenerateSelfLink(false), true);
            partnersConfiguration.HasSingletonBinding(c => c.Company, singletonName);
            Func<EntityInstanceContext<Partner>, IEdmNavigationProperty, Uri> link = (eic, np) => eic.GenerateNavigationPropertyLink(np, false);
            partnersConfiguration.HasNavigationPropertyLink(partnerCompany, link, true);
            partnersConfiguration.EntityType.Collection.Action("ResetDataSource");

            SingletonConfiguration<Company> companyConfiguration = builder.Singleton<Company>(singletonName);
            companyConfiguration.HasIdLink(c => c.GenerateSelfLink(false), true);
            companyConfiguration.HasManyBinding(c => c.Partners, "Partners");
            Func<EntityInstanceContext<Company>, IEdmNavigationProperty, Uri> linkFactory = (eic, np) => eic.GenerateNavigationPropertyLink(np, false);
            companyConfiguration.HasNavigationPropertyLink(companyPartners, linkFactory, true);
            companyConfiguration.EntityType.Action("ResetDataSource");
            companyConfiguration.EntityType.Function("GetPartnersCount").Returns<int>();

            return builder.GetEdmModel();
        }
示例#3
0
        public void CreateEnumTypeWithFlags()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var color = builder.EnumType<Color>();
            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);

            // Act
            var model = builder.GetEdmModel();
            var colorType = model.SchemaElements.OfType<IEdmEnumType>().Single();

            // Assert
            Assert.Equal("Color", colorType.Name);
            Assert.True(colorType.IsFlags);
            Assert.Equal(3, colorType.Members.Count());
            Assert.Equal("Edm.Int32", colorType.UnderlyingType.FullName());

            var redMember = colorType.Members.SingleOrDefault(m => m.Name == "Red");
            var greenMember = colorType.Members.SingleOrDefault(m => m.Name == "Green");
            var blueMember = colorType.Members.SingleOrDefault(m => m.Name == "Blue");

            Assert.NotNull(redMember);
            Assert.NotNull(greenMember);
            Assert.NotNull(blueMember);
        }
        public void CreateQueryOptions_SetsContextProperties_WithModelAndPath()
        {
            // Arrange
            ApiController controller = new Mock<ApiController>().Object;
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/Customers");
            controller.Configuration = new HttpConfiguration();
            ODataModelBuilder odataModel = new ODataModelBuilder();
            string setName = typeof(Customer).Name;
            odataModel.EntityType<Customer>().HasKey(c => c.Id);
            odataModel.EntitySet<Customer>(setName);
            IEdmModel model = odataModel.GetEdmModel();
            IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet(setName);
            request.ODataProperties().Model = model;
            request.ODataProperties().Path = new ODataPath(new EntitySetPathSegment(entitySet));
            controller.Request = request;

            // Act
            ODataQueryOptions<Customer> queryOptions =
                EntitySetControllerHelpers.CreateQueryOptions<Customer>(controller);

            // Assert
            Assert.Same(model, queryOptions.Context.Model);
            Assert.Same(entitySet, queryOptions.Context.NavigationSource);
            Assert.Same(typeof(Customer), queryOptions.Context.ElementClrType);
        }
        public void CanUseRelativeLinks()
        {
            var builder = new ODataModelBuilder()
                            .Add_Customer_EntityType()
                            .Add_Order_EntityType()
                            .Add_CustomerOrders_Relationship()
                            .Add_Customers_EntitySet()
                            .Add_Orders_EntitySet()
                            .Add_CustomerOrders_Binding();


            var customersSet = builder.EntitySet<Customer>("Customers");
            customersSet.HasEditLink(o => new Uri(string.Format("Customers({0})", o.EntityInstance.CustomerId), UriKind.Relative));
            customersSet.FindBinding("Orders").HasLinkFactory(o => string.Format("Orders/ByCustomerId/{0}", ((Customer)o.EntityInstance).CustomerId));

            var model = builder.GetEdmModel();

            var container = model.FindDeclaredEntityContainer("Container");
            var customerEdmEntitySet = container.FindEntitySet("Customers");
            // TODO: Fix later, need to add a reference
            //var entityContext = new EntityInstanceContext<Customer>(model, customerEdmEntitySet, (IEdmEntityType)customerEdmEntitySet.ElementType, null, new Customer { CustomerId = 24 });

            //Assert.Equal("Customers", customersSet.GetUrl());
            ///Assert.Equal("Customers(24)", customersSet.GetEditLink(entityContext).ToString());
            //Assert.Equal("Orders/ByCustomerId/24", customersSet.FindBinding("Orders").GetLink(entityContext));
        }
        public void CanBuildBoundProcedureCacheForIEdmModel()
        {
            // Arrange            
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
            customer.HasKey(c => c.ID);
            customer.Property(c => c.Name);
            customer.ComplexProperty(c => c.Address);

            EntityTypeConfiguration<Movie> movie = builder.EntitySet<Movie>("Movies").EntityType;
            movie.HasKey(m => m.ID);
            movie.HasKey(m => m.Name);
            EntityTypeConfiguration<Blockbuster> blockBuster = builder.Entity<Blockbuster>().DerivesFrom<Movie>();
            EntityTypeConfiguration movieConfiguration = builder.StructuralTypes.OfType<EntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to a single entity
            customer.Action("InCache1_CustomerAction");
            customer.Action("InCache2_CustomerAction");
            movie.Action("InCache3_MovieAction");
            ActionConfiguration incache4_MovieAction = builder.Action("InCache4_MovieAction");
            incache4_MovieAction.SetBindingParameter("bindingParameter", movieConfiguration, true);
            blockBuster.Action("InCache5_BlockbusterAction");

            // build actions that are either: bindable to a collection of entities, have no parameter, have only complex parameter 
            customer.Collection.Action("NotInCache1_CustomersAction");
            movie.Collection.Action("NotInCache2_MoviesAction");
            ActionConfiguration notInCache3_NoParameters = builder.Action("NotInCache3_NoParameters");
            ActionConfiguration notInCache4_AddressParameter = builder.Action("NotInCache4_AddressParameter");
            notInCache4_AddressParameter.Parameter<Address>("address");

            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Customer");
            IEdmEntityType movieType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Movie");
            IEdmEntityType blockBusterType = model.SchemaElements.OfType<IEdmEntityType>().Single(e => e.Name == "Blockbuster");

            // Act 
            BindableProcedureFinder annotation = new BindableProcedureFinder(model);
            IEdmAction[] movieActions = annotation.FindProcedures(movieType)
                .OfType<IEdmAction>()
                .ToArray();
            IEdmAction[] customerActions = annotation.FindProcedures(customerType)
                .OfType<IEdmAction>()
                .ToArray();
            IEdmAction[] blockBusterActions = annotation.FindProcedures(blockBusterType)
                .OfType<IEdmAction>()
                .ToArray();

            // Assert
            Assert.Equal(2, customerActions.Length);
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache1_CustomerAction"));
            Assert.NotNull(customerActions.SingleOrDefault(a => a.Name == "InCache2_CustomerAction"));
            Assert.Equal(2, movieActions.Length);
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(movieActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.Equal(3, blockBusterActions.Length);
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache3_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache4_MovieAction"));
            Assert.NotNull(blockBusterActions.SingleOrDefault(a => a.Name == "InCache5_BlockbusterAction"));
        }
示例#7
0
 private static IEdmModel GetModel()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     var customers = builder.EntitySet<PropertyCustomer>("PropertyCustomers");
     customers.EntityType.HasKey(x => x.Id);
     customers.HasIdLink(c => "http://localhost:12345", true);
     customers.EntityType.Property(p => p.Name);
     return builder.GetEdmModel();
 }
 public UnboundFunctionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     FunctionConfiguration function = builder.Function("TopCustomer");
     function.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Function("MyFunction").Returns<string>();
     _model = builder.GetEdmModel();
     _container = _model.EntityContainers().Single();
 }
        public ComplexTypeTest()
        {
            ODataModelBuilder model = new ODataModelBuilder();
            var person = model.ComplexType<Person>();
            person.Property(p => p.Age);
            person.Property(p => p.FirstName);
            person.ComplexProperty(p => p.FavoriteHobby);
            person.ComplexProperty(p => p.Gender);

            _formatter = new ODataMediaTypeFormatter(model.GetEdmModel()) { IsClient = true };
        }
 public UnboundActionPathSegmentTest()
 {
     ODataModelBuilder builder = new ODataModelBuilder();
     builder.EntityType<MyCustomer>().HasKey(c => c.Id).Property(c => c.Name);
     builder.EntitySet<MyCustomer>("Customers");
     ActionConfiguration action = builder.Action("CreateCustomer");
     action.ReturnsFromEntitySet<MyCustomer>("Customers");
     builder.Action("MyAction").Returns<string>();
     builder.Action("ActionWithoutReturn");
     _model = builder.GetEdmModel();
     _container = _model.EntityContainer;
 }
示例#11
0
        public static IEdmModel GetTypedExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var accountType = builder.EntityType<Account>();
            accountType.HasKey(c => c.Id);
            accountType.Property(c => c.Name);
            accountType.HasDynamicProperties(c => c.DynamicProperties);

            accountType.ComplexProperty<AccountInfo>(c => c.AccountInfo);
            accountType.ComplexProperty<Address>(a => a.Address);
            accountType.ComplexProperty<Tags>(a => a.Tags);

            var premiumAccountType = builder.EntityType<PremiumAccount>();
            premiumAccountType.Property(p => p.Since);
            premiumAccountType.DerivesFrom<Account>();

            var accountInfoType = builder.ComplexType<AccountInfo>();
            accountInfoType.Property(i => i.NickName);
            accountInfoType.HasDynamicProperties(i => i.DynamicProperties);

            var addressType = builder.ComplexType<Address>();
            addressType.Property(a => a.City);
            addressType.Property(a => a.Street);
            addressType.HasDynamicProperties(a => a.DynamicProperties);

            var globalAddressType = builder.ComplexType<GlobalAddress>();
            globalAddressType.Property(a => a.CountryCode);
            globalAddressType.DerivesFrom<Address>();

            var tagsType = builder.ComplexType<Tags>();
            tagsType.HasDynamicProperties(t => t.DynamicProperties);

            var gender = builder.EnumType<Gender>();
            gender.Member(Gender.Female);
            gender.Member(Gender.Male);

            var employeeType = builder.EntityType<Employee>();
            employeeType.HasKey(e => e.Id);
            employeeType.HasOptional(e => e.Account);
            builder.EntitySet<Employee>("Employees");

            var managerType = builder.EntityType<Manager>();
            managerType.Property(m => m.Heads);
            managerType.HasDynamicProperties(m => m.DynamicProperties);
            managerType.DerivesFrom<Employee>();

            AddBoundActionsAndFunctions(accountType);
            AddUnboundActionsAndFunctions(builder);

            EntitySetConfiguration<Account> accounts = builder.EntitySet<Account>("Accounts");
            builder.Namespace = typeof(Account).Namespace;
            return builder.GetEdmModel();
        }
示例#12
0
        public static IEdmModel GetEdmModel()
        {
            var builder = new ODataModelBuilder();

            var employee = builder.EntityType<Employee>();
            employee.HasKey(e => e.EmployeeID);
            employee.HasMany(e => e.Orders);

            var order = builder.EntityType<Order>();
            order.HasKey(c => c.OrderID);
            order.HasMany(c => c.OrderDetails);

            return builder.GetEdmModel();
        }
示例#13
0
        public void CreateEnumTypeWithoutFlags()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var simple = builder.EnumType<SimpleEnum>();
            simple.Member(SimpleEnum.First);
            simple.Member(SimpleEnum.Second);
            simple.Member(SimpleEnum.Third);

            // Act
            var model = builder.GetEdmModel();
            var colorType = model.SchemaElements.OfType<IEdmEnumType>().Single();

            // Assert
            Assert.False(colorType.IsFlags);
        }
示例#14
0
        private static IEdmModel CreateModelForFullMetadata(bool sameLinksForIdAndEdit, bool sameLinksForEditAndRead)
        {
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            EntitySetConfiguration <MainEntity> mainSet = builder.EntitySet <MainEntity>("MainEntity");

            Func <EntityInstanceContext <MainEntity>, Uri> idLinkFactory = (e) =>
                                                                           CreateAbsoluteUri("/MainEntity/id/" + e.GetPropertyValue("Id").ToString());

            mainSet.HasIdLink(idLinkFactory, followsConventions: true);

            if (!sameLinksForIdAndEdit)
            {
                Func <EntityInstanceContext <MainEntity>, Uri> editLinkFactory =
                    (e) => CreateAbsoluteUri("/MainEntity/edit/" + e.GetPropertyValue("Id").ToString());
                mainSet.HasEditLink(editLinkFactory, followsConventions: false);
            }

            if (!sameLinksForEditAndRead)
            {
                Func <EntityInstanceContext <MainEntity>, Uri> readLinkFactory =
                    (e) => CreateAbsoluteUri("/MainEntity/read/" + e.GetPropertyValue("Id").ToString());
                mainSet.HasReadLink(readLinkFactory, followsConventions: false);
            }

            EntityTypeConfiguration <MainEntity> main = mainSet.EntityType;

            main.HasKey <int>((e) => e.Id);
            main.Property <short>((e) => e.Int16);
            NavigationPropertyConfiguration mainToRelated = mainSet.EntityType.HasRequired((e) => e.Related);

            main.Action("DoAlways").ReturnsCollectionFromEntitySet <MainEntity>("MainEntity").HasActionLink((c) =>
                                                                                                            CreateAbsoluteUri("/MainEntity/DoAlways/" + c.GetPropertyValue("Id")),
                                                                                                            followsConventions: true);
            main.Action("DoSometimes").ReturnsCollectionFromEntitySet <MainEntity>(
                "MainEntity").HasActionLink((c) =>
                                            CreateAbsoluteUri("/MainEntity/DoSometimes/" + c.GetPropertyValue("Id")),
                                            followsConventions: false);

            mainSet.HasNavigationPropertyLink(mainToRelated, (c, p) => new Uri("/MainEntity/RelatedEntity/" +
                                                                               c.GetPropertyValue("Id"), UriKind.Relative), followsConventions: true);

            EntitySetConfiguration <RelatedEntity> related = builder.EntitySet <RelatedEntity>("RelatedEntity");

            return(builder.GetEdmModel());
        }
示例#15
0
        public void CreateEdmModel_WithSingleton_CanAddBindingPath_ToNavigationProperty_WithComplex()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            var motorcycle = builder.AddEntityType(typeof(Motorcycle));
            var myMotor    = builder.AddSingleton("MyMotor", motorcycle);

            var manufacturer = builder.AddComplexType(typeof(MotorcycleManufacturer));
            var address      = builder.AddEntityType(typeof(ManufacturerAddress));

            motorcycle.AddComplexProperty(typeof(Motorcycle).GetProperty("Manufacturer"));
            var navProperty = manufacturer.AddNavigationProperty(typeof(Manufacturer).GetProperty("Address"), EdmMultiplicity.One);

            var addresses = builder.AddEntitySet("Addresses", address);

            myMotor.AddBinding(navProperty, addresses, new List <MemberInfo>
            {
                typeof(Motorcycle).GetProperty("Manufacturer"),
                typeof(Manufacturer).GetProperty("Address")
            });

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

            // Assert
            var motorcycleEdmType = model.AssertHasEntityType(typeof(Motorcycle));

            Assert.Empty(motorcycleEdmType.NavigationProperties());

            var manufacturerEdmType = model.AssertHasComplexType(typeof(MotorcycleManufacturer));

            var edmNavProperty = manufacturerEdmType.AssertHasNavigationProperty(model, "Address",
                                                                                 typeof(ManufacturerAddress), isNullable: false, multiplicity: EdmMultiplicity.One);

            var myMotorSingleton = model.EntityContainer.FindSingleton("MyMotor");

            Assert.NotNull(myMotorSingleton);

            var bindings = myMotorSingleton.FindNavigationPropertyBindings(edmNavProperty);
            var binding  = Assert.Single(bindings);

            Assert.Equal("Address", binding.NavigationProperty.Name);
            Assert.Equal("Addresses", binding.Target.Name);
            Assert.Equal("Manufacturer/Address", binding.Path.Path);
        }
示例#16
0
        public void CanConfigureManyProperty_MultipleBindingPath_For_NavigationProperties_WithComplex()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();

            builder
            .EntitySet <BindingCustomer>("Customers")
            .Binding
            .HasManyPath(c => c.Addresses)
            .HasManyBinding(a => a.Cities, "Cities");

            // 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());
            IEdmProperty addressesProperty = Assert.Single(customer.Properties());

            Assert.Equal("Addresses", addressesProperty.Name);
            Assert.Equal(EdmPropertyKind.Structural, addressesProperty.PropertyKind);
            Assert.True(addressesProperty.Type.IsCollection());

            // "BindingAddress" complex type
            var address        = model.AssertHasComplexType(typeof(BindingAddress));
            var citiesProperty = address.AssertHasNavigationProperty(model, "Cities", typeof(BindingCity), isNullable: true, multiplicity: EdmMultiplicity.Many);
            var bindings       = customers.FindNavigationPropertyBindings(citiesProperty);
            IEdmNavigationPropertyBinding binding = Assert.Single(bindings);

            Assert.Equal("Cities", binding.NavigationProperty.Name);
            Assert.Equal("Cities", binding.Target.Name);
            Assert.Equal("Addresses/Cities", binding.Path.Path);

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

            Assert.Same(navSource, binding.Target);

            // "BindingCity" entity type
            model.AssertHasEntityType(typeof(BindingCity));
        }
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // 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");
            IEdmModel model = builder.GetEdmModel();

            var customers = model.FindDeclaredEntitySet("Customers");

            var request = RequestFactory.CreateFromModel(model);

            EntitySetSegment entitySetSegment = new EntitySetSegment(customers);
            ODataPath        odataPath        = new ODataPath(new[] { entitySetSegment });

            request.ODataContext().Path = odataPath;

            Dictionary <string, object> properties = new Dictionary <string, object> {
                { "Name", "Foo" }
            };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);

            if (header.Equals("IfMatch"))
            {
                request.Headers.AddIfMatch(etagHeaderValue);
            }
            else
            {
                request.Headers.AddIfNoneMatch(etagHeaderValue);
            }

            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));

            // Act
            IODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, request);
            ETag    result        = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
示例#18
0
        public void GetEdmModel_ThrowsException_WhenBoundActionOverloaded()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            customer.Action("ActionOnCustomer");
            customer.Action("ActionOnCustomer").Returns <string>();

            // Act & Assert
            ExceptionAssert.Throws <InvalidOperationException>(() => builder.GetEdmModel(),
                                                               "Found more than one action with name 'ActionOnCustomer' " +
                                                               "bound to the same type 'Microsoft.AspNet.OData.Test.Builder.TestModels.Customer'. " +
                                                               "Each bound action must have a different binding type or name.");
        }
示例#19
0
        public void GetTargetNavigationSource_Returns_Model_WithoutStackOverflow()
        {
            // Arrange
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.ContainerName = "ThisContainer";
            builder.Namespace     = "ThisNamespace";

            builder.EntityType <RecursivePropertyContainer>().HasKey(p => p.Id);
            builder.EntitySet <RecursivePropertyContainer>("Containers");

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

            // Assert
            Assert.NotNull(model);
        }
        public async Task TenantGet()
        {
            //Mock obujects

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

            ODataModelBuilder builder = Aparte.ModelBuilder.AparteModelBuilder.GetOdataModelBuilder();
            var model = builder.GetEdmModel();

            HttpRouteCollection routes = new HttpRouteCollection();
            HttpConfiguration   config = new HttpConfiguration(routes)
            {
                IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
            };


            config.MapODataServiceRoute("ODataV4Route", "aparte", model);
            config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);

            config.EnableDependencyInjection();
            //Check all the routes are properly initialized.
            config.EnsureInitialized();

            request.SetConfiguration(config);
            ODataQueryContext context = new ODataQueryContext(
                model,
                typeof(Tenant),
                new ODataPath(
                    new Microsoft.OData.UriParser.EntitySetSegment(
                        model.EntityContainer.FindEntitySet("Tenants"))
                    )
                );


            var controller = new TenantsController();

            controller.Request = request;

            var options  = new ODataQueryOptions <Tenant>(context, request);
            var response = await(controller.Get() as IHttpActionResult).ExecuteAsync(CancellationToken.None);

            List <Tenant> tenants = await response.Content.ReadAsAsync <List <Tenant> >();

            Assert.IsTrue(tenants.Any());
        }
示例#21
0
        private static IEdmModel GetExplicitEdmModel()
        {
            // Non-conventional model builder
            // http://odata.github.io/WebApi/#02-03-model-builder-nonconvention

            var builder = new ODataModelBuilder();

            // enum type "Color"
            var color = builder.EnumType <Color>();

            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);
            color.Member(Color.Yellow);
            color.Member(Color.Pink);
            color.Member(Color.Purple);

            // complex type "Address"
            var address = builder.ComplexType <Address>();

            address.Property(a => a.City);
            address.Property(a => a.Street);

            // entity type "Customer"
            var customer = builder.EntityType <Customer>().HasKey(c => c.CustomerId);

            customer.Property(c => c.Name);
            customer.Property(c => c.Token);
            // customer.Property(c => c.Email).IsNotNavigable(); // you can call Fluent API
            customer.Property(c => c.Email);
            customer.CollectionProperty(c => c.Addresses);
            customer.CollectionProperty(c => c.FavoriateColors);
            customer.HasMany(c => c.Orders);

            // entity type "Order"
            var order = builder.EntityType <Order>().HasKey(o => o.OrderId);

            order.Property(o => o.Price);

            // entity sets
            builder.EntitySet <Customer>("Customers").HasManyBinding(c => c.Orders, "Orders");
            builder.EntitySet <Order>("Orders");

            return(builder.GetEdmModel());
        }
        public void GetEntry_UsesRouteModel_ForMultipleModels()
        {
            // Model 1 only has Name, Model 2 only has Age
            ODataModelBuilder builder1 = new ODataModelBuilder();
            var personType1 = builder1.EntityType<FormatterPerson>();
            personType1.HasKey(p => p.PerId);
            personType1.Property(p => p.Name);
            builder1.EntitySet<FormatterPerson>("People").HasIdLink(p => new Uri("http://link/"), false);
            var model1 = builder1.GetEdmModel();

            ODataModelBuilder builder2 = new ODataModelBuilder();
            var personType2 = builder2.EntityType<FormatterPerson>();
            personType2.HasKey(p => p.PerId);
            personType2.Property(p => p.Age);
            builder2.EntitySet<FormatterPerson>("People").HasIdLink(p => new Uri("http://link/"), false);
            var model2 = builder2.GetEdmModel();

            var config = new[] { typeof(PeopleController) }.GetHttpConfiguration();
            config.MapODataServiceRoute("OData1", "v1", model1);
            config.MapODataServiceRoute("OData2", "v2", model2);

            using (HttpServer host = new HttpServer(config))
            using (HttpClient client = new HttpClient(host))
            {
                using (HttpResponseMessage response = client.GetAsync("http://localhost/v1/People(10)").Result)
                {
                    Assert.True(response.IsSuccessStatusCode);
                    JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                    // Model 1 has the Name property but not the Age property
                    Assert.NotNull(json["Name"]);
                    Assert.Null(json["Age"]);
                }

                using (HttpResponseMessage response = client.GetAsync("http://localhost/v2/People(10)").Result)
                {
                    Assert.True(response.IsSuccessStatusCode);
                    JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                    // Model 2 has the Age property but not the Name property
                    Assert.Null(json["Name"]);
                    Assert.NotNull(json["Age"]);
                }
            }
        }
示例#23
0
        private static void ConfigureOData(HttpConfiguration config)
        {
            var builder  = new ODataModelBuilder();
            var itemType = builder.EntityType <Item>();

            itemType.HasKey(i => i.Id);
            itemType.Property(i => i.Name);
            itemType.Property(i => i.Value);
            itemType.HasDynamicProperties(i => i.DynamicProperties);
            builder.EntitySet <Item>("items");

            config.MapODataServiceRoute(
                routeName: "ODataRoute",
                routePrefix: "odata",
                model: builder.GetEdmModel());
            config.Count().Filter().Select().OrderBy();
            config.AddODataQueryFilter();
        }
示例#24
0
        public void GetIfMatchOrNoneMatch_ETagIsNull_IfETagHeaderValueNotSet(string header)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            IEdmModel         model   = builder.GetEdmModel();
            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions <Customer> query = new ODataQueryOptions <Customer>(context, new HttpRequestMessage());
            ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;

            // Assert
            Assert.Null(result);
        }
示例#25
0
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var fileType = builder.EntityType<File>().HasKey(f => f.FileId);
            fileType.Property(f => f.Name);
            fileType.Property(f => f.CreatedDate);
            fileType.Property(f => f.DeleteDate);
            fileType.CollectionProperty(f => f.ModifiedDates);

            var files = builder.EntitySet<File>("Files");
            files.HasIdLink(link, true);
            files.HasEditLink(link, true);

            BuildFunctions(builder);
            BuildActions(builder);

            return builder.GetEdmModel();
        }
示例#26
0
        public void GetEdmModel_WorksOnModelBuilder_ForOpenComplexType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ComplexTypeConfiguration<SimpleOpenComplexType> complex = builder.ComplexType<SimpleOpenComplexType>();
            complex.Property(c => c.IntProperty);
            complex.HasDynamicProperties(c => c.DynamicProperties);

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

            // Assert
            Assert.NotNull(model);
            IEdmComplexType complexType = Assert.Single(model.SchemaElements.OfType<IEdmComplexType>());
            Assert.True(complexType.IsOpen);
            IEdmProperty edmProperty = Assert.Single(complexType.Properties());
            Assert.Equal("IntProperty", edmProperty.Name);
        }
        public void GetEdmModel_DoesntCreateOperationImport_For_BoundedOperations()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntitySetConfiguration <Customer> customers = builder.EntitySet <Customer>("Customers");

            customers.EntityType.HasKey(c => c.Id);
            customers.EntityType.Action("Action").Returns <bool>();
            customers.EntityType.Collection.Action("CollectionAction").Returns <bool>();
            customers.EntityType.Function("Function").Returns <bool>();
            customers.EntityType.Collection.Function("Function").Returns <bool>();

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

            // Assert
            Assert.Empty(model.EntityContainer.OperationImports());
        }
示例#28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ODataModelBuilder modelBuilder)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseMvc(routeBuilder =>
            {
                routeBuilder.MapODataServiceRoute("odata", "odata", modelBuilder.GetEdmModel(app.ApplicationServices));
            });
        }
示例#29
0
        public void Querying_Enum_Collections(IQueryable queryable, string query, object result)
        {
            // Arrange
            ODataModelBuilder  odataModel = new ODataModelBuilder().Add_SimpleEnum_EnumType();
            IEdmModel          model      = odataModel.GetEdmModel();
            HttpRequestMessage request    = new HttpRequestMessage(HttpMethod.Get, "http://localhost/?" + query);
            ODataQueryContext  context    = new ODataQueryContext(model, queryable.ElementType);
            ODataQueryOptions  options    = new ODataQueryOptions(context, request);

            // Act
            queryable = options.ApplyTo(queryable);

            // Assert
            IEnumerator enumerator = queryable.GetEnumerator();

            Assert.True(enumerator.MoveNext());
            Assert.Equal(result, enumerator.Current);
        }
示例#30
0
        public void CreateNullableEnumType()
        {
            // Arrange
            var builder = new ODataModelBuilder().Add_Color_EnumType();
            var complexTypeConfiguration = builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            complexTypeConfiguration.EnumProperty(c => c.NullableColor);

            // Act
            var model = builder.GetEdmModel();
            var complexType = model.SchemaElements.OfType<IEdmStructuredType>().Single();

            // Assert
            Assert.Equal(1, complexType.Properties().Count());
            var nullableColor = complexType.Properties().SingleOrDefault(p => p.Name == "NullableColor");
            Assert.NotNull(nullableColor);
            Assert.True(nullableColor.Type.IsEnum());
            Assert.True(nullableColor.Type.IsNullable);
        }
        private static IEdmModel CreateModel()
        {
            Mock <ODataModelBuilder> mock = new Mock <ODataModelBuilder>();

            mock.Setup(b => b.ValidateModel(It.IsAny <IEdmModel>())).Callback(() => { });
            mock.CallBase = true;
            ODataModelBuilder builder = mock.Object;
            EntitySetConfiguration <Entity> entities = builder.EntitySet <Entity>("entities");

            builder.EntitySet <RelatedEntity>("related");
            NavigationPropertyConfiguration entityToRelated =
                entities.EntityType.HasOptional <RelatedEntity>((e) => e.Related);

            // entities.HasNavigationPropertyLink(entityToRelated, (a, b) => new Uri("aa:b"), false);
            entities.HasOptionalBinding((e) => e.Related, "related");

            return(builder.GetEdmModel());
        }
        public void GetEdmModel_SetsNullableIfParameterTypeIsReferenceType()
        {
            // Arrange
            ODataModelBuilder builder             = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            var actionBuilder = movie.Action("Watch");

            actionBuilder.Parameter <string>("string").Nullable = false;
            actionBuilder.Parameter <string>("nullaleString");

            actionBuilder.Parameter <Address>("address").Nullable = false;
            actionBuilder.Parameter <Address>("nullableAddress");

            actionBuilder.EntityParameter <Customer>("customer").Nullable = false;
            actionBuilder.EntityParameter <Customer>("nullableCustomer");

            actionBuilder.CollectionParameter <Address>("addresses").Nullable = false;
            actionBuilder.CollectionParameter <Address>("nullableAddresses");

            actionBuilder.CollectionEntityParameter <Customer>("customers").Nullable = false;
            actionBuilder.CollectionEntityParameter <Customer>("nullableCustomers");

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

            //Assert
            IEdmOperation action = Assert.Single(model.SchemaElements.OfType <IEdmAction>());

            Assert.False(action.FindParameter("string").Type.IsNullable);
            Assert.True(action.FindParameter("nullaleString").Type.IsNullable);

            Assert.False(action.FindParameter("address").Type.IsNullable);
            Assert.True(action.FindParameter("nullableAddress").Type.IsNullable);

            Assert.False(action.FindParameter("customer").Type.IsNullable);
            Assert.True(action.FindParameter("nullableCustomer").Type.IsNullable);

            Assert.False(action.FindParameter("addresses").Type.IsNullable);
            Assert.True(action.FindParameter("nullableAddresses").Type.IsNullable);

            // Follow up: https://github.com/OData/odata.net/issues/98
            // Assert.False(action.FindParameter("customers").Type.IsNullable);
            Assert.True(action.FindParameter("nullableCustomers").Type.IsNullable);
        }
        public void HasMany_NavigationPropertyTest()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var customer = builder.EntityType <Customer>().HasKey(c => c.Id);
            var city     = builder.EntityType <City>().HasKey(c => c.Id);
            var address  = builder.ComplexType <Address>();

            address.HasMany(a => a.Cities);

            HttpClient client = GetClient(builder.GetEdmModel());

            string requestUri = "http://localhost/odata/$metadata";
            string result     = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                                "<edmx:Edmx Version=\"4.0\" xmlns:edmx=\"http://docs.oasis-open.org/odata/ns/edmx\">" +
                                "<edmx:DataServices><Schema Namespace=\"ModelLibrary\" xmlns=\"http://docs.oasis-open.org/odata/ns/edm\">" +
                                "<EntityType Name=\"Customer\">" +
                                "<Key>" +
                                "<PropertyRef Name=\"Id\" />" +
                                "</Key>" +
                                "<Property Name=\"Id\" Type=\"Edm.Int32\" Nullable=\"false\" />" +
                                "</EntityType>" +
                                "<EntityType Name=\"City\">" +
                                "<Key>" +
                                "<PropertyRef Name=\"Id\" />" +
                                "</Key>" +
                                "<Property Name=\"Id\" Type=\"Edm.Int32\" Nullable=\"false\" />" +
                                "</EntityType>" +
                                "<ComplexType Name=\"Address\">" +
                                "<NavigationProperty Name=\"Cities\" Type=\"Collection(ModelLibrary.City)\" />" +
                                "</ComplexType>" +
                                "</Schema>" +
                                "<Schema Namespace=\"Default\" xmlns=\"http://docs.oasis-open.org/odata/ns/edm\">" +
                                "<EntityContainer Name=\"Container\" />" +
                                "</Schema>" +
                                "</edmx:DataServices>" +
                                "</edmx:Edmx>";

            HttpRequestMessage  request  = new HttpRequestMessage(new HttpMethod("Get"), requestUri);
            HttpResponseMessage response = client.SendAsync(request).Result;

            response.EnsureSuccessStatusCode();
            _output.WriteLine(response.Content.ReadAsStringAsync().Result);
            Assert.Equal(result, response.Content.ReadAsStringAsync().Result);
        }
示例#34
0
        public void CanConfigureDerivedTypeConstraints()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntitySet <Creature>("Creatures").EntityType.HasKey(c => c.Id);
            builder.EntityType <Animal>().DerivesFrom <Creature>();
            builder.EntityType <Human>().DerivesFrom <Creature>();
            builder.EntityType <Gene>().DerivesFrom <Creature>(); // No restriction
            builder.EntityType <StateZoo>().DerivesFrom <Zoo>();  // No restriction
            builder.EntityType <NationZoo>().DerivesFrom <Zoo>();
            builder.EntityType <SeaZoo>().DerivesFrom <Zoo>();
            var zooType = builder.EntityType <Zoo>();

            var function = zooType.Function("MyFunction").ReturnsFromEntitySet <Creature>("Creatures");

            function.BindingParameter.HasDerivedTypeConstraint <SeaZoo>().HasDerivedTypeConstraint <NationZoo>();
            function.HasDerivedTypeConstraintForReturnType <Animal>().HasDerivedTypeConstraintForReturnType <Human>();
            function.ReturnTypeConstraints.Location = Microsoft.OData.Edm.Csdl.EdmVocabularyAnnotationSerializationLocation.OutOfLine;

            function.BindingParameter.DerivedTypeConstraints.Location = Microsoft.OData.Edm.Csdl.EdmVocabularyAnnotationSerializationLocation.OutOfLine;

            IEdmModel model = builder.GetEdmModel();

            string csdl = MetadataTest.GetCSDL(model);

            Assert.NotNull(csdl);

            Assert.Contains("<Annotations Target=\"Default.MyFunction(Microsoft.AspNet.OData.Test.Builder.TestModels.Zoo)/$ReturnType\">" +
                            "<Annotation Term=\"Org.OData.Validation.V1.DerivedTypeConstraint\">" +
                            "<Collection>" +
                            "<String>Microsoft.AspNet.OData.Test.Builder.TestModels.Animal</String>" +
                            "<String>Microsoft.AspNet.OData.Test.Builder.TestModels.Human</String>" +
                            "</Collection>" +
                            "</Annotation>" +
                            "</Annotations>" +
                            "<Annotations Target=\"Default.MyFunction(Microsoft.AspNet.OData.Test.Builder.TestModels.Zoo)/bindingParameter\">" +
                            "<Annotation Term=\"Org.OData.Validation.V1.DerivedTypeConstraint\">" +
                            "<Collection>" +
                            "<String>Microsoft.AspNet.OData.Test.Builder.TestModels.SeaZoo</String>" +
                            "<String>Microsoft.AspNet.OData.Test.Builder.TestModels.NationZoo</String>" +
                            "</Collection>" +
                            "</Annotation>" +
                            "</Annotations>", csdl);
        }
示例#35
0
        static IEdmModel GetEdmModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            //builder
            //    .Entity<IVehicle>()

            //builder
            //    .Entity<IVehicle1>()

            builder
            .Entity <Vehicle>()
            .Abstract()
            .HasKey(v => v.Name)
            .HasKey(v => v.Model)
            .Property(v => v.WheelCount);

            var motocycle = builder
                            .Entity <Motorcycle>()
                            .DerivesFrom <Vehicle>();

            motocycle.Property(m => m.CanDoAWheelie);
            motocycle.HasMany(m => m.Vehicles);
            motocycle.HasMany(m => m.Motocycles);
            motocycle.HasMany(m => m.SportBikes);

            builder
            .Entity <Car>()
            .DerivesFrom <Vehicle>()
            .Property(c => c.SeatingCapacity);

            builder
            .Entity <SportBike>()
            .DerivesFrom <Motorcycle>()
            .Property(b => b.TopSpeed);

            var vechicles  = builder.EntitySet <Vehicle>("vehicles");
            var motocycles = builder.EntitySet <Motorcycle>("motorcycles");
            var cars       = builder.EntitySet <Car>("cars");
            var sportBikes = builder.EntitySet <SportBike>("sportBikes");


            return(builder.GetEdmModel());
        }
        public void GetEntry_UsesRouteModel_ForMultipleModels()
        {
            // Model 1 only has Name, Model 2 only has Age
            ODataModelBuilder builder1 = new ODataModelBuilder();
            var personType1            = builder1.Entity <FormatterPerson>().Property(p => p.Name);

            builder1.EntitySet <FormatterPerson>("People").HasIdLink(p => "link", false);
            var model1 = builder1.GetEdmModel();

            ODataModelBuilder builder2 = new ODataModelBuilder();

            builder2.Entity <FormatterPerson>().Property(p => p.Age);
            builder2.EntitySet <FormatterPerson>("People").HasIdLink(p => "link", false);
            var model2 = builder2.GetEdmModel();

            var config = new HttpConfiguration();

            config.Routes.MapODataRoute("OData1", "v1", model1);
            config.Routes.MapODataRoute("OData2", "v2", model2);

            using (HttpServer host = new HttpServer(config))
                using (HttpClient client = new HttpClient(host))
                {
                    using (HttpResponseMessage response = client.GetAsync("http://localhost/v1/People(10)").Result)
                    {
                        Assert.True(response.IsSuccessStatusCode);
                        JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                        // Model 1 has the Name property but not the Age property
                        Assert.NotNull(json["Name"]);
                        Assert.Null(json["Age"]);
                    }

                    using (HttpResponseMessage response = client.GetAsync("http://localhost/v2/People(10)").Result)
                    {
                        Assert.True(response.IsSuccessStatusCode);
                        JToken json = JToken.Parse(response.Content.ReadAsStringAsync().Result);

                        // Model 2 has the Age property but not the Name property
                        Assert.Null(json["Name"]);
                        Assert.NotNull(json["Age"]);
                    }
                }
        }
示例#37
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.Equal("Cities_A, Cities_B", String.Join(", ", bindings.Select(e => e.Target.Name)));
            Assert.Equal("Location/City, Address/City", String.Join(", ", bindings.Select(e => e.Path.Path)));

            // "BindingCity" entity type
            model.AssertHasEntityType(typeof(BindingCity));
        }
        public void Match_DeterminesExpectedServiceRoot_ForFunctionCallWithEscapedSeparator(
            string prefixString,
            string oDataString)
        {
            // Arrange
            var originalRoot = "http://any/" + prefixString;
            var expectedRoot = originalRoot;

            if (!String.IsNullOrEmpty(prefixString))
            {
                originalRoot += "%2F";  // Escaped '/'
            }

            var oDataPath           = String.Format("Unbound(p0='{0}')", oDataString);
            var request             = new HttpRequestMessage(HttpMethod.Get, originalRoot + oDataPath);
            var httpRouteCollection = new HttpRouteCollection
            {
                { _routeName, new HttpRoute() },
            };

            request.SetConfiguration(new HttpConfiguration(httpRouteCollection));

            var builder = new ODataModelBuilder();

            builder.Function("Unbound").Returns <string>().Parameter <string>("p0");
            var model = builder.GetEdmModel();

            var pathHandler = new TestPathHandler();
            var constraint  = new ODataPathRouteConstraint(pathHandler, model, _routeName, _conventions);
            var values      = new Dictionary <string, object>
            {
                { ODataRouteConstants.ODataPath, Uri.UnescapeDataString(oDataPath) },
            };

            // Act
            var matched = constraint.Match(request, null, null, values, HttpRouteDirection.UriResolution);

            // Assert
            Assert.True(matched);
            Assert.NotNull(pathHandler.ServiceRoot);
            Assert.Equal(expectedRoot, pathHandler.ServiceRoot);
            Assert.NotNull(pathHandler.ODataPath);
            Assert.Equal(oDataPath, pathHandler.ODataPath);
        }
示例#39
0
        public void CanCreateFunctionWithCollectionReturnTypeViaEntitySetPath()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            EntityTypeConfiguration <Order>    order    = builder.EntityType <Order>();

            customer.HasMany <Order>(c => c.Orders);
            FunctionConfiguration getOrders = customer.Function("GetOrders").ReturnsCollectionViaEntitySetPath <Order>("bindingParameter/Orders");

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

            // Assert
            IEdmFunction function = Assert.Single(model.SchemaElements.OfType <IEdmFunction>());

            Assert.Equal(EdmExpressionKind.Path, function.EntitySetPath.ExpressionKind);
            Assert.Equal("bindingParameter/Orders", string.Join("/", ((IEdmPathExpression)(function.EntitySetPath)).Path));
        }
示例#40
0
        private static IEdmModel GetModel()
        {
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.ContainerName = "Container";
            builder.Namespace     = "org.odata";
            // Action with no overloads
            builder.EntitySet <Vehicle>("Vehicles").EntityType.Action("Drive");
            builder.Singleton <Vehicle>("MyVehicle");
            // Valid overloads of "Wash" bound to different entities
            builder.EntityType <Motorcycle>().Action("Wash");
            builder.EntityType <Car>().Action("Wash");
            builder.EntityType <Car>().Action("NSAction").Namespace = "customize";

            EdmModel model = (EdmModel)builder.GetEdmModel();

            // Invalid overloads of action "Park". These two actions must have different names or binding types
            // but differ only in that the second has a 'mood' parameter.
            IEdmEntityType entityType = model.SchemaElements.OfType <IEdmEntityType>().Single(e => e.Name == "Car");
            var            park       = new EdmAction(
                "org.odata",
                "Park",
                returnType: null,
                isBound: true,
                entitySetPathExpression: null);

            park.AddParameter("bindingParameter", new EdmEntityTypeReference(entityType, isNullable: false));
            model.AddElement(park);

            IEdmTypeReference stringType = EdmCoreModel.Instance.GetPrimitive(EdmPrimitiveTypeKind.String, isNullable: true);

            park = new EdmAction(
                "org.odata",
                "Park",
                returnType: null,
                isBound: true,
                entitySetPathExpression: null);
            park.AddParameter("bindingParameter", new EdmEntityTypeReference(entityType, isNullable: false));
            park.AddParameter("mood", stringType);
            model.AddElement(park);

            return(model);
        }
示例#41
0
        public void CanCreateFunctionWithEntityReturnTypeViaEntitySetPath()
        {
            // Arrange
            ODataModelBuilder builder = ODataModelBuilderMocks.GetModelBuilderMock();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();
            EntityTypeConfiguration <Order>    order    = builder.EntityType <Order>();

            order.HasRequired <Customer>(o => o.Customer);
            FunctionConfiguration getOrderCustomer = order.Function("GetOrderCustomer").ReturnsEntityViaEntitySetPath <Customer>("bindingParameter/Customer");

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

            // Assert
            IEdmFunction function = Assert.Single(model.SchemaElements.OfType <IEdmFunction>());

            Assert.Equal(EdmExpressionKind.Path, function.EntitySetPath.ExpressionKind);
            Assert.Equal("bindingParameter/Customer", string.Join("/", ((IEdmPathExpression)(function.EntitySetPath)).Path));
        }
示例#42
0
        public void CanCreateAbstractEntityTypeWithoutKey()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <BaseAbstractShape>().Abstract();

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

            // Assert
            IEdmEntityType baseShapeType =
                model.SchemaElements.OfType <IEdmEntityType>().FirstOrDefault(e => e.Name == "BaseAbstractShape");

            Assert.NotNull(baseShapeType);
            Assert.True(baseShapeType.IsAbstract);
            Assert.Null(baseShapeType.DeclaredKey);
            Assert.Empty(baseShapeType.Properties());
        }
示例#43
0
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var fileType = builder.EntityType <File>().HasKey(f => f.FileId);

            fileType.Property(f => f.Name);
            fileType.Property(f => f.CreatedDate);
            fileType.Property(f => f.DeleteDate);

            var files = builder.EntitySet <File>("Files");

            files.HasIdLink(link, true);
            files.HasEditLink(link, true);

            BuildFunctions(builder);
            BuildActions(builder);

            return(builder.GetEdmModel());
        }
示例#44
0
        public void Cant_SetFunctionTitle_OnNonBindableFunctions()
        {
            // Arrange
            ODataModelBuilder     builder  = new ODataModelBuilder();
            FunctionConfiguration function = builder.Function("MyFunction");

            function.Returns <int>();
            function.Title = "My Function";

            // Act
            IEdmModel           model          = builder.GetEdmModel();
            IEdmOperationImport functionImport = model.EntityContainer.OperationImports().OfType <IEdmFunctionImport>().Single();

            Assert.NotNull(functionImport);
            OperationTitleAnnotation functionTitleAnnotation = model.GetOperationTitleAnnotation(functionImport.Operation);

            // Assert
            Assert.Null(functionTitleAnnotation);
        }
示例#45
0
        public static IEdmModel BuildCustomerEdmModel()
        {
            var builder = new ODataModelBuilder();

            builder.EntitySet <Customer>("Customers");

            var customerType = builder.EntityType <Customer>();

            customerType.HasKey(c => c.Id).Ignore(c => c.Location);
            customerType.Ignore(c => c.Line);
            customerType.Property(c => c.Name);

            // Cannot call customerType.Property(c => c.HomeLocation)
            var customer = builder.StructuralTypes.First(t => t.ClrType == typeof(Customer));

            customer.AddProperty(typeof(Customer).GetProperty("EdmLocation")).Name = "Location";
            customer.AddProperty(typeof(Customer).GetProperty("EdmLine")).Name     = "Line";
            return(builder.GetEdmModel());
        }
        private IEdmModel GetModel <T>() where T : class
        {
            Type      key = typeof(T);
            IEdmModel value;

            if (!_modelCache.TryGetValue(key, out value))
            {
                ODataModelBuilder model = ODataConventionModelBuilderFactory.Create();
                model.EntitySet <T>("Products");
                if (key == typeof(Product))
                {
                    model.EntityType <DerivedProduct>().DerivesFrom <Product>();
                    model.EntityType <DerivedCategory>().DerivesFrom <Category>();
                }

                value = _modelCache[key] = model.GetEdmModel();
            }
            return(value);
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Window> windowType = builder.EntityType<Window>();
            windowType.HasKey(a => a.Id);
            windowType.Property(a => a.Name).IsRequired();
            windowType.ComplexProperty(w => w.CurrentShape);
            windowType.CollectionProperty(w => w.OptionalShapes);
            windowType.HasOptional<Window>(w => w.Parent);

            ComplexTypeConfiguration<Shape> shapeType = builder.ComplexType<Shape>();
            shapeType.Property(s => s.HasBorder);
            shapeType.Abstract();

            ComplexTypeConfiguration<Circle> circleType = builder.ComplexType<Circle>();
            circleType.ComplexProperty(c => c.Center);
            circleType.Property(c => c.Radius);
            circleType.DerivesFrom<Shape>();

            ComplexTypeConfiguration<Polygon> polygonType = builder.ComplexType<Polygon>();
            polygonType.CollectionProperty(p => p.Vertexes);
            polygonType.DerivesFrom<Shape>();

            ComplexTypeConfiguration<Rectangle> rectangleType = builder.ComplexType<Rectangle>();
            rectangleType.ComplexProperty(r => r.TopLeft);
            rectangleType.Property(r => r.Width);
            rectangleType.Property(r => r.Height);
            rectangleType.DerivesFrom<Polygon>();

            ComplexTypeConfiguration<Point> pointType = builder.ComplexType<Point>();
            pointType.Property(p => p.X);
            pointType.Property(p => p.Y);

            EntitySetConfiguration<Window> windows = builder.EntitySet<Window>("Windows");
            windows.HasEditLink(link, true);
            windows.HasIdLink(link, true);

            builder.Namespace = typeof(Window).Namespace;

            return builder.GetEdmModel();
        }
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var accountType = builder.EntityType<Account>();
            accountType.HasKey(a => a.AccountID);
            accountType.Property(a => a.Name);
            var payoutPI = accountType.ContainsOptional(a => a.PayoutPI);
            var payinPIs = accountType.HasMany(a => a.PayinPIs)
                .Contained();

            var premiumAccountType = builder.EntityType<PremiumAccount>()
                .DerivesFrom<Account>();
            var giftCard = premiumAccountType.ContainsRequired(pa => pa.GiftCard);

            var giftCardType = builder.EntityType<GiftCard>();
            giftCardType.HasKey(g => g.GiftCardID);
            giftCardType.Property(g => g.GiftCardNO);
            giftCardType.Property(g => g.Amount);

            var paymentInstrumentType = builder.EntityType<PaymentInstrument>();
            paymentInstrumentType.HasKey(pi => pi.PaymentInstrumentID);
            paymentInstrumentType.Property(pi => pi.FriendlyName);
            var statement = paymentInstrumentType.ContainsOptional(pi => pi.Statement);

            var statementType = builder.EntityType<Statement>();
            statementType.HasKey(s => s.StatementID);
            statementType.Property(s => s.TransactionDescription);
            statementType.Property(s => s.Amount);

            var accounts = builder.EntitySet<Account>("Accounts"); 
            accounts.HasIdLink(c => c.GenerateSelfLink(false), true);
            accounts.HasEditLink(c => c.GenerateSelfLink(true), true);
            
            builder.Singleton<Account>("AnonymousAccount");

            AddBoundActionsAndFunctions(builder);

            builder.Namespace = typeof(Account).Namespace;

            return builder.GetEdmModel();
        }
示例#49
0
        public void CanAddBinding_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);
            vehicles.AddBinding(navProperty, manufacturers);

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

            Assert.Equal(
                "manufacturers",
                model.EntityContainers().Single().FindEntitySet("vehicles").FindNavigationTarget(edmNavProperty).Name);
        }
        public void GetIfMatchOrNoneMatch_ReturnsETag_SetETagHeaderValue(string header)
        {
            // Arrange
            HttpRequestMessage request = new HttpRequestMessage();
            HttpConfiguration cofiguration = new HttpConfiguration();
            request.SetConfiguration(cofiguration);
            Dictionary<string, object> properties = new Dictionary<string, object> { { "Name", "Foo" } };
            EntityTagHeaderValue etagHeaderValue = new DefaultODataETagHandler().CreateETag(properties);
            if (header.Equals("IfMatch"))
            {
                request.Headers.IfMatch.Add(etagHeaderValue);
            }
            else
            {
                request.Headers.IfNoneMatch.Add(etagHeaderValue);
            }

            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.Entity<Customer>();
            customer.HasKey(c => c.Id);
            customer.Property(c => c.Id);
            customer.Property(c => c.Name).IsConcurrencyToken();
            IEdmModel model = builder.GetEdmModel();

            Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true };
            mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer)));
            mockSegment.Setup(s => s.GetEntitySet(null)).Returns((IEdmEntitySet)null);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });
            request.SetODataPath(odataPath);
            ODataQueryContext context = new ODataQueryContext(model, typeof(Customer));

            // Act
            ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, request);
            ETag result = header.Equals("IfMatch") ? query.IfMatch : query.IfNoneMatch;
            dynamic dynamicResult = result;

            // Assert
            Assert.Equal("Foo", result["Name"]);
            Assert.Equal("Foo", dynamicResult.Name);
        }
示例#51
0
        public static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var employee = builder.EntityType<Employee>();
            employee.HasKey(c => c.ID);
            employee.Property(c => c.Name);
            employee.CollectionProperty<Skill>(c => c.SkillSet);
            employee.EnumProperty<Gender>(c => c.Gender);
            employee.EnumProperty<AccessLevel>(c => c.AccessLevel);
            employee.ComplexProperty<FavoriteSports>(c => c.FavoriteSports);

            var skill = builder.EnumType<Skill>();
            skill.Member(Skill.CSharp);
            skill.Member(Skill.Sql);
            skill.Member(Skill.Web);

            var gender = builder.EnumType<Gender>();
            gender.Member(Gender.Female);
            gender.Member(Gender.Male);

            var accessLevel = builder.EnumType<AccessLevel>();
            accessLevel.Member(AccessLevel.Execute);
            accessLevel.Member(AccessLevel.Read);
            accessLevel.Member(AccessLevel.Write);

            var favoriteSports = builder.ComplexType<FavoriteSports>();
            favoriteSports.EnumProperty<Sport>(f => f.LikeMost);
            favoriteSports.CollectionProperty<Sport>(f => f.Like);

            var sport = builder.EnumType<Sport>();
            sport.Member(Sport.Basketball);
            sport.Member(Sport.Pingpong);

            AddBoundActionsAndFunctions(employee);
            AddUnboundActionsAndFunctions(builder);

            EntitySetConfiguration<Employee> employees = builder.EntitySet<Employee>("Employees");
            builder.Namespace = typeof(Employee).Namespace;
            return builder.GetEdmModel();
        }
示例#52
0
        private static IEdmModel GetExplicitEdmModel()
        {
            var builder = new ODataModelBuilder();

            // enum type "Color"
            var color = builder.EnumType<Color>();
            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);
            color.Member(Color.Yellow);
            color.Member(Color.Pink);
            color.Member(Color.Purple);

            // complex type "Address"
            var address = builder.ComplexType<Address>();
            address.Property(a => a.City);
            address.Property(a => a.Street);

            // entity type "Customer"
            var customer = builder.EntityType<Customer>().HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            customer.Property(c => c.Token);
            // customer.Property(c => c.Email).IsNotNavigable(); // you can call Fluent API
            customer.Property(c => c.Email);
            customer.CollectionProperty(c => c.Addresses);
            customer.CollectionProperty(c => c.FavoriateColors);
            customer.HasMany(c => c.Orders);

            // entity type "Order"
            var order = builder.EntityType<Order>().HasKey(o => o.OrderId);
            order.Property(o => o.Price);

            // entity sets
            builder.EntitySet<Customer>("Customers").HasManyBinding(c => c.Orders, "Orders");
            builder.EntitySet<Order>("Orders");

            return builder.GetEdmModel();
        }
示例#53
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);
        }
示例#54
0
        public void CannotBindNavigationPropertyAutmatically_WhenMultipleEntitySetsOfPropertyType_Exist()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntitySet<Motorcycle>("motorcycles1").HasRequiredBinding(m => m.Manufacturer, "NorthWestMotorcycleManufacturers");
            builder.EntitySet<Motorcycle>("motorcycles2");
            builder.EntitySet<MotorcycleManufacturer>("NorthWestMotorcycleManufacturers");
            builder.EntitySet<MotorcycleManufacturer>("SouthWestMotorcycleManufacturers");

            Assert.Throws<NotSupportedException>(
            () => builder.GetEdmModel(),
            "Cannot automatically bind the navigation property 'Manufacturer' on entity type 'System.Web.Http.OData.Builder.TestModels.Motorcycle' for the source entity set 'motorcycles2' because there are two or more matching target entity sets. " +
            "The matching entity sets are: NorthWestMotorcycleManufacturers, SouthWestMotorcycleManufacturers.");
        }
示例#55
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.EntityInstance.Model, ctxt.EntityInstance.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);

            Uri link = model.GetEntitySetLinkBuilder(vehicles).BuildNavigationLink(
                new EntityInstanceContext { EntityInstance = new Motorcycle { Name = "Motorcycle1", Model = 2009 }, EdmModel = model, EntitySet = vehicles, EntityType = motorcycle },
                motorcycleManufacturerProperty,
                ODataMetadataLevel.Default);

            Assert.Equal("http://localhost/vehicles/2009/Motorcycle1/Manufacturer", link.AbsoluteUri);
        }
示例#56
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);
        }
示例#57
0
        private static IEdmModel CreateModelForFullMetadata(bool sameLinksForIdAndEdit, bool sameLinksForEditAndRead)
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            EntitySetConfiguration<MainEntity> mainSet = builder.EntitySet<MainEntity>("MainEntity");

            Func<EntityInstanceContext<MainEntity>, string> idLinkFactory = (e) =>
                CreateAbsoluteLink("/MainEntity/id/" + e.GetPropertyValue("Id").ToString());
            mainSet.HasIdLink(idLinkFactory, followsConventions: true);

            Func<EntityInstanceContext<MainEntity>, string> editLinkFactory;

            if (!sameLinksForIdAndEdit)
            {
                editLinkFactory = (e) => CreateAbsoluteLink("/MainEntity/edit/" + e.GetPropertyValue("Id").ToString());
                mainSet.HasEditLink(editLinkFactory, followsConventions: false);
            }

            Func<EntityInstanceContext<MainEntity>, string> readLinkFactory;

            if (!sameLinksForEditAndRead)
            {
                readLinkFactory = (e) => CreateAbsoluteLink("/MainEntity/read/" + e.GetPropertyValue("Id").ToString());
                mainSet.HasReadLink(readLinkFactory, followsConventions: false);
            }

            EntityTypeConfiguration<MainEntity> main = mainSet.EntityType;

            main.HasKey<int>((e) => e.Id);
            main.Property<short>((e) => e.Int16);
            NavigationPropertyConfiguration mainToRelated = mainSet.EntityType.HasRequired((e) => e.Related);

            main.Action("DoAlways").ReturnsCollectionFromEntitySet<MainEntity>("MainEntity").HasActionLink((c) =>
                CreateAbsoluteUri("/MainEntity/DoAlways/" + c.GetPropertyValue("Id")),
                followsConventions: true);
            main.TransientAction("DoSometimes").ReturnsCollectionFromEntitySet<MainEntity>(
                "MainEntity").HasActionLink((c) =>
                    CreateAbsoluteUri("/MainEntity/DoSometimes/" + c.GetPropertyValue("Id")),
                    followsConventions: false);

            mainSet.HasNavigationPropertyLink(mainToRelated, (c, p) => new Uri("/MainEntity/RelatedEntity/" +
                c.GetPropertyValue("Id"), UriKind.Relative), followsConventions: true);

            EntitySetConfiguration<RelatedEntity> related = builder.EntitySet<RelatedEntity>("RelatedEntity");

            return builder.GetEdmModel();
        }
示例#58
0
        public void CreateEdmModel_WithSingletons_AndSingletonBindingToSingleton()
        {
            // Arrange
            var builder = new ODataModelBuilder()
                .Add_Company_EntityType()
                .Add_Employee_EntityType()
                .Add_CompanyEmployees_Relationship();

            // Singleton -> Singleton
            builder.Singleton<Company>("OsCorp").HasSingletonBinding(c => c.CEO, "Boss");

            // Act & Assert
            var model = builder.GetEdmModel();
            Assert.NotNull(model);

            var container = model.SchemaElements.OfType<IEdmEntityContainer>().SingleOrDefault();
            Assert.NotNull(container);

            var osCorp = container.FindSingleton("OsCorp");
            Assert.NotNull(osCorp);

            var gates = container.FindSingleton("Boss");
            Assert.NotNull(gates);

            var vipCompanyVipEmployee = osCorp.NavigationPropertyBindings.FirstOrDefault(nt => nt.NavigationProperty.Name == "CEO");
            Assert.NotNull(vipCompanyVipEmployee);
            Assert.Same(gates, vipCompanyVipEmployee.Target);
            Assert.Equal("Boss", vipCompanyVipEmployee.Target.Name);
        }
示例#59
0
        public static IEdmModel GetEdmModel()
        {
            if (_model == null)
            {
                ODataModelBuilder model = new ODataModelBuilder();

                var color = model.EnumType<Color>();
                color.Member(Color.Red);
                color.Member(Color.Green);
                color.Member(Color.Blue);

                var people = model.EntitySet<FormatterPerson>("People");
                people.HasFeedSelfLink(context => new Uri(context.Url.CreateODataLink(new EntitySetPathSegment(
                    context.EntitySetBase))));
                people.HasIdLink(context =>
                    {
                        return new Uri(context.Url.CreateODataLink(
                            new EntitySetPathSegment(context.NavigationSource as IEdmEntitySet),
                            new KeyValuePathSegment(context.GetPropertyValue("PerId").ToString())));
                    },
                    followsConventions: false);

                var person = people.EntityType;
                person.HasKey(p => p.PerId);
                person.Property(p => p.Age);
                person.Property(p => p.MyGuid);
                person.Property(p => p.Name);
                person.EnumProperty(p => p.FavoriteColor);
                person.ComplexProperty<FormatterOrder>(p => p.Order);

                var order = model.ComplexType<FormatterOrder>();
                order.Property(o => o.OrderAmount);
                order.Property(o => o.OrderName);

                // Add a top level function without parameter and the "IncludeInServiceDocument = true"
                var getPerson = model.Function("GetPerson");
                getPerson.ReturnsFromEntitySet<FormatterPerson>("People");
                getPerson.IncludeInServiceDocument = true;

                // Add a top level function without parameter and the "IncludeInServiceDocument = false"
                var getAddress = model.Function("GetAddress");
                getAddress.Returns<string>();
                getAddress.IncludeInServiceDocument = false;

                // Add an overload top level function with parameters and the "IncludeInServiceDocument = true"
                getPerson = model.Function("GetPerson");
                getPerson.Parameter<int>("PerId");
                getPerson.ReturnsFromEntitySet<FormatterPerson>("People");
                getPerson.IncludeInServiceDocument = true;

                // Add an overload top level function with parameters and the "IncludeInServiceDocument = false"
                getAddress = model.Function("GetAddress");
                getAddress.Parameter<int>("AddressId");
                getAddress.Returns<string>();
                getAddress.IncludeInServiceDocument = false;

                // Add an overload top level function
                var getVipPerson = model.Function("GetVipPerson");
                getVipPerson.Parameter<string>("name");
                getVipPerson.ReturnsFromEntitySet<FormatterPerson>("People");
                getVipPerson.IncludeInServiceDocument = true;

                // Add a top level function which is included in service document
                getVipPerson = model.Function("GetVipPerson");
                getVipPerson.ReturnsFromEntitySet<FormatterPerson>("People");
                getVipPerson.IncludeInServiceDocument = true;

                // Add an overload top level function
                getVipPerson = model.Function("GetVipPerson");
                getVipPerson.Parameter<int>("PerId");
                getVipPerson.Parameter<string>("name");
                getVipPerson.ReturnsFromEntitySet<FormatterPerson>("People");
                getVipPerson.IncludeInServiceDocument = true;

                // Add a top level function with parameters and without any overload
                var getSalary = model.Function("GetSalary");
                getSalary.Parameter<int>("PerId");
                getSalary.Parameter<string>("month");
                getSalary.Returns<int>();
                getSalary.IncludeInServiceDocument = true;

                // Add Singleton
                var president = model.Singleton<FormatterPerson>("President");
                president.HasIdLink(context =>
                    {
                        return new Uri(context.Url.CreateODataLink(new SingletonPathSegment((IEdmSingleton)context.NavigationSource)));
                    },
                    followsConventions: false);

                _model = model.GetEdmModel();
            }

            return _model;
        }
        private static IEdmModel GetEdmModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            // Configure LimitedEntity
            EntitySetConfiguration<LimitedEntity> limitedEntities = builder.EntitySet<LimitedEntity>("LimitedEntities");
            limitedEntities.EntityType.HasKey(p => p.Id);
            limitedEntities.EntityType.ComplexProperty(c => c.ComplexProperty);
            limitedEntities.EntityType.CollectionProperty(c => c.ComplexCollectionProperty).IsNotCountable();
            limitedEntities.EntityType.HasMany(l => l.EntityCollectionProperty).IsNotCountable();
            limitedEntities.EntityType.CollectionProperty(cp => cp.Integers).IsNotCountable();

            // Configure LimitedRelatedEntity
            EntitySetConfiguration<LimitedRelatedEntity> limitedRelatedEntities =
                builder.EntitySet<LimitedRelatedEntity>("LimitedRelatedEntities");
            limitedRelatedEntities.EntityType.HasKey(p => p.Id);
            limitedRelatedEntities.EntityType.CollectionProperty(p => p.ComplexCollectionProperty).IsNotCountable();

            // Configure Complextype
            ComplexTypeConfiguration<LimitedComplex> complexType = builder.ComplexType<LimitedComplex>();
            complexType.CollectionProperty(p => p.Strings).IsNotCountable();
            complexType.Property(p => p.Value);
            complexType.CollectionProperty(p => p.SimpleEnums).IsNotCountable();

            // Configure EnumType
            EnumTypeConfiguration<SimpleEnum> enumType = builder.EnumType<SimpleEnum>();
            enumType.Member(SimpleEnum.First);
            enumType.Member(SimpleEnum.Second);
            enumType.Member(SimpleEnum.Third);
            enumType.Member(SimpleEnum.Fourth);

            return builder.GetEdmModel();
        }