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();
        }
        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"));
        }
Example #3
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();
        }
        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 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();
        }
        public static IEdmModel GetEdmModel()
        {
            if (_model == null)
            {
                ODataModelBuilder model = new ODataModelBuilder();

                var people = model.EntitySet<FormatterPerson>("People");
                people.HasIdLink(context => context.UrlHelper.Link(ODataRouteNames.GetById, new { Id = (context.EntityInstance as FormatterPerson).PerId }));
                people.HasEditLink(context => new Uri(context.UrlHelper.Link(ODataRouteNames.GetById, new { Id = (context.EntityInstance as FormatterPerson).PerId })));
                people.HasReadLink(context => new Uri(context.UrlHelper.Link(ODataRouteNames.GetById, new { Id = (context.EntityInstance as FormatterPerson).PerId })));

                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.ComplexProperty<FormatterOrder>(p => p.Order);

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

                _model = model.GetEdmModel();
            }

            return _model;
        }
Example #7
0
        public static IEdmModel GetEdmModel()
        {
            if (_model == null)
            {
                ODataModelBuilder model = new ODataModelBuilder();

                var people = model.EntitySet<FormatterPerson>("People");
                people.HasFeedSelfLink(context => new Uri(context.Url.ODataLink(new EntitySetPathSegment(
                    context.EntitySet))));
                people.HasIdLink(context =>
                    {
                        return context.Url.ODataLink(
                            new EntitySetPathSegment(context.EntitySet),
                            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.ComplexProperty<FormatterOrder>(p => p.Order);

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

                _model = model.GetEdmModel();
            }

            return _model;
        }
        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();
        }
        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));
        }
Example #10
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 void CreateModelWithEntitySet()
        {
            var builder = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet();
            builder.EntitySet<Customer>("Customers");

            var model = builder.GetServiceModel();
            var container = model.SchemaElements.OfType<IEdmEntityContainer>().SingleOrDefault();
            Assert.NotNull(container);
            var customers = container.EntitySets().SingleOrDefault(e => e.Name == "Customers");
            Assert.NotNull(customers);
            Assert.Equal("Customer", customers.ElementType.Name);
        }
 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;
 }
Example #14
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();
        }
        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.EntitySet))));
                people.HasIdLink(context =>
                    {
                        return context.Url.CreateODataLink(
                            new EntitySetPathSegment(context.EntitySet),
                            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 
                var getPersons = model.Function("GetPerson");
                getPersons.Parameter<Int32>("PerId");
                getPersons.ReturnsFromEntitySet<FormatterPerson>("People");

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

                _model = model.GetEdmModel();
            }

            return _model;
        }
Example #16
0
        public static IEdmModel GetEdmModel()
        {
            if (_model == null)
            {
                ODataModelBuilder model = new ODataModelBuilder();

                var people = model.EntitySet<FormatterPerson>("People");
                people.HasFeedSelfLink(context => new Uri(context.UrlHelper.Link(ODataRouteConstants.RouteName, new { })));
                people.HasIdLink(context => 
                    {
                        string selfLink = context.EntitySet.Name + "(" + (context.EntityInstance as FormatterPerson).PerId.ToString() + ")";
                        return context.UrlHelper.Link(
                            ODataRouteConstants.RouteName,
                            new HttpRouteValueDictionary() { { "odataPath", selfLink } });
                    });

                people.HasEditLink(context =>
                {
                    string selfLink = context.EntitySet.Name + "(" + (context.EntityInstance as FormatterPerson).PerId.ToString() + ")";
                    return context.UrlHelper.Link(
                        ODataRouteConstants.RouteName,
                        new HttpRouteValueDictionary() { { "odataPath", selfLink } });
                });

                people.HasReadLink(context => 
                    {
                        string selfLink = context.EntitySet.Name + "(" + (context.EntityInstance as FormatterPerson).PerId.ToString() + ")";
                        return context.UrlHelper.Link(
                            ODataRouteConstants.RouteName,
                            new HttpRouteValueDictionary() { { "odataPath", selfLink } });
                    });

                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.ComplexProperty<FormatterOrder>(p => p.Order);

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

                _model = model.GetEdmModel();
            }

            return _model;
        }
        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"]);
                }
            }
        }
Example #18
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();
        }
        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.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");
            Mock<ODataPathSegment> mockSegment = new Mock<ODataPathSegment> { CallBase = true };
            mockSegment.Setup(s => s.GetEdmType(null)).Returns(model.GetEdmType(typeof(Customer)));
            mockSegment.Setup(s => s.GetNavigationSource(null)).Returns((IEdmNavigationSource)customers);
            ODataPath odataPath = new ODataPath(new[] { mockSegment.Object });
            request.ODataProperties().Path = odataPath;
            request.ODataProperties().Model = model;
            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);
        }
        public void BuilderIncludesMapFromEntityTypeToBindableProcedures()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
            customer.HasKey(c => c.Id);
            customer.Property(c => c.Name);
            customer.Action("Reward");
            IEdmModel model = builder.GetEdmModel();
            IEdmEntityType customerType = model.SchemaElements.OfType<IEdmEntityType>().SingleOrDefault();

            // Act
            BindableProcedureFinder finder = model.GetAnnotationValue<BindableProcedureFinder>(model);

            // Assert
            Assert.NotNull(finder);
            Assert.NotNull(finder.FindProcedures(customerType).SingleOrDefault());
            Assert.Equal("Reward", finder.FindProcedures(customerType).SingleOrDefault().Name);
        }
        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();
        }
Example #23
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();
        }
        /// <summary>
        /// Applies model configurations using the provided builder for the specified API version.
        /// </summary>
        /// <param name="builder">The <see cref="ODataModelBuilder">builder</see> used to apply configurations.</param>
        /// <param name="apiVersion">The <see cref="ApiVersion">API version</see> associated with the <paramref name="builder"/>.</param>
        public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
        {
            var order = builder.EntitySet <Order>("Orders").EntityType.HasKey(o => o.Id);

            if (apiVersion < ApiVersions.V2)
            {
                order.Ignore(o => o.EffectiveDate);
            }

            if (apiVersion < ApiVersions.V3)
            {
                order.Ignore(o => o.Description);
            }

            if (apiVersion >= ApiVersions.V1)
            {
                order.Collection.Function("MostExpensive").ReturnsFromEntitySet <Order>("Orders");
            }

            if (apiVersion >= ApiVersions.V2)
            {
                order.Action("Rate").Parameter <int>("rating");
            }
        }
Example #25
0
        public void CanManuallyConfigureFeedActionLinkFactory()
        {
            // Arrange
            Uri expectedUri           = new Uri("http://localhost/service/Customers/Reward");
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);
            ActionConfiguration reward = customer.Collection.Action("Reward");

            reward.HasFeedActionLink(ctx => expectedUri, followsConventions: false);
            IEdmModel model = builder.GetEdmModel();

            // Act
            IEdmAction           rewardAction      = Assert.Single(model.SchemaElements.OfType <IEdmAction>()); // Guard
            OperationLinkBuilder actionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(rewardAction);
            ResourceSetContext   context           = new ResourceSetContext();

            //Assert
            Assert.Equal(expectedUri, reward.GetFeedActionLink()(context));
            Assert.NotNull(actionLinkBuilder);
            Assert.Equal(expectedUri, actionLinkBuilder.BuildLink(context));
        }
Example #26
0
        private static void MapPECMailOData(ODataModelBuilder builder)
        {
            builder
            .EntitySet <PECMailModel>("PECMails")
            .EntityType.HasKey(p => p.Id);


            #region [ Functions ]
            FunctionConfiguration getPECMailsFunc = builder
                                                    .EntityType <PECMailModel>().Collection
                                                    .Function("GetProtocolPECMails");

            getPECMailsFunc.Namespace = "PECMailService";
            getPECMailsFunc.ReturnsCollectionFromEntitySet <PECMailModel>("PECMails");
            getPECMailsFunc.Parameter <short>("year");
            getPECMailsFunc.Parameter <int>("number");
            getPECMailsFunc.Parameter <short>("direction");

            #endregion

            #region [ Navigation Properties ]

            #endregion
        }
Example #27
0
        private static void MapDocumentUnitReferenceOData(ODataModelBuilder builder)
        {
            builder
            .EntitySet <DocumentUnitReferenceModel>("DocumentUnitReferences")
            .EntityType.HasKey(p => p.Id);

            #region [ Functions ]

            FunctionConfiguration getByContacts = builder
                                                  .EntityType <DocumentUnitReferenceModel>().Collection
                                                  .Function("ProtocolByContacts")
                                                  .ReturnsCollectionFromEntitySet <DocumentUnitReferenceModel>("DocumentUnitReferences");

            getByContacts.Namespace = "FinderService";
            getByContacts.Parameter <string>("searchCode");
            getByContacts.Parameter <DateTimeOffset?>("dateFrom");
            getByContacts.Parameter <DateTimeOffset?>("dateTo");

            #endregion

            #region [ Navigation Properties ]

            #endregion
        }
Example #28
0
        private static IEdmModel GetEdmModel(ODataModelBuilder builder)
        {
            EntitySetConfiguration <Tarea> tasks = builder.EntitySet <Tarea>("Tareas");

            builder.ContainerName      = "DefaultContainer";
            tasks.EntityType.Name      = "Tarea";
            tasks.EntityType.Namespace = "AspNetCoreODataWithModel.Data.Entities";

            tasks.EntityType.Property(p => p.Id).Name            = "Id";
            tasks.EntityType.Property(p => p.Nombre).Name        = "Name";
            tasks.EntityType.Property(p => p.Fecha).Name         = "Date";
            tasks.EntityType.Property(p => p.Facturable).Name    = "Billable";
            tasks.EntityType.Property(p => p.Observaciones).Name = "Observations";

            tasks.EntityType
            .Filter()
            .Count()
            .Expand()
            .OrderBy()
            .Page()
            .Select();

            return(builder.GetEdmModel());
        }
Example #29
0
        private IEdmModel GetModel()
        {
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.ContainerName = "Container";
            builder.Namespace     = "org.odata";
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;
            ActionConfiguration action = customer.Action("DoSomething");

            action.Parameter <int>("p1");
            action.Parameter <Address>("p2");
            action.Parameter <Color?>("color");
            action.CollectionParameter <string>("p3");
            action.CollectionParameter <Address>("p4");
            action.CollectionParameter <Color?>("colors");

            action = customer.Collection.Action("MyAction");
            action.EntityParameter <Customer>("Customer");
            action.CollectionEntityParameter <Customer>("Customers");

            action           = customer.Action("CNSAction");
            action.Namespace = "customize";
            return(builder.GetEdmModel());
        }
        public void WhenFunctionLinksNotManuallyConfigured_ConventionBasedBuilderUsesConventions()
        {
            // Arrange
            string            uriTemplate         = "http://server/Movies({0})/Default.Watch(param=@param)";
            Uri               expectedUri         = new Uri(string.Format(uriTemplate, 1));
            ODataModelBuilder builder             = ODataConventionModelBuilderFactory.Create();
            EntityTypeConfiguration <Movie> movie = builder.EntitySet <Movie>("Movies").EntityType;
            FunctionConfiguration           watch = movie.Function("Watch").Returns <int>();

            watch.Parameter <string>("param");
            IEdmModel model = builder.GetEdmModel();

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

            configuration.MapODataServiceRoute(routeName, null, model);

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

            // Act
            IEdmEntityType         movieType         = model.SchemaElements.OfType <IEdmEntityType>().SingleOrDefault();
            IEdmEntityContainer    container         = model.SchemaElements.OfType <IEdmEntityContainer>().SingleOrDefault();
            IEdmFunction           watchFunction     = Assert.Single(model.SchemaElements.OfType <IEdmFunction>()); // Guard
            IEdmEntitySet          entitySet         = container.EntitySets().SingleOrDefault();
            ODataSerializerContext serializerContext = ODataSerializerContextFactory.Create(model, entitySet, request);

            ResourceContext context = new ResourceContext(serializerContext, movieType.AsReference(), new Movie {
                ID = 1, Name = "Avatar"
            });
            OperationLinkBuilder functionLinkBuilder = model.GetAnnotationValue <OperationLinkBuilder>(watchFunction);

            //Assert
            Assert.Equal(expectedUri, watch.GetFunctionLink()(context));
            Assert.NotNull(functionLinkBuilder);
            Assert.Equal(expectedUri, functionLinkBuilder.BuildLink(context));
        }
        public void HasOptionalBinding_AddBindindToNavigationSource_Derived()
        {
            // Assert
            ODataModelBuilder builder = new ODataModelBuilder();
            var customerType          = builder.EntityType <BindingCustomer>();
            var navigationSource      = builder.EntitySet <BindingCustomer>("Customers");

            StructuralTypeConfiguration addressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingAddress");

            Assert.Null(addressType);                                                  // Guard
            Assert.Empty(customerType.Properties);                                     // Guard
            Assert.Null(builder.EntitySets.FirstOrDefault(e => e.Name == "Cities_D")); // Guard

            // Act
            new BindingPathConfiguration <BindingCustomer>(builder, customerType, navigationSource.Configuration)
            .HasSinglePath((BindingVipCustomer v) => v.VipLocation)
            .HasOptionalBinding((BindingUsAddress u) => u.UsCity, "Cities_D");

            // Assert
            var usAddressType = builder.StructuralTypes.FirstOrDefault(c => c.Name == "BindingUsAddress");

            Assert.NotNull(usAddressType);
            PropertyConfiguration citiesProperty = Assert.Single(usAddressType.Properties);

            Assert.Equal("UsCity", citiesProperty.Name);

            NavigationPropertyConfiguration navigationProperty = Assert.IsType <NavigationPropertyConfiguration>(citiesProperty);

            Assert.Equal(EdmMultiplicity.ZeroOrOne, navigationProperty.Multiplicity);

            var bindings = navigationSource.FindBinding(navigationProperty);
            var binding  = Assert.Single(bindings);

            Assert.Equal("Cities_D", binding.TargetNavigationSource.Name);
            Assert.Equal("Microsoft.Test.AspNet.OData.Formatter.BindingVipCustomer/VipLocation/Microsoft.Test.AspNet.OData.Formatter.BindingUsAddress/UsCity", binding.BindingPath);
        }
        public void ReturnsCollectionFromEntitySet_Sets_EntitySetAndReturnType()
        {
            // Arrange
            string entitySetName = "movies";
            ODataModelBuilder builder = new ODataModelBuilder();
            var movies = builder.EntitySet<Movie>(entitySetName);
            var action = builder.Action("Action");

            // Act
            action.ReturnsCollectionFromEntitySet(movies);

            // Assert
            Assert.Equal(entitySetName, action.EntitySet.Name);
            Assert.Equal(typeof(IEnumerable<Movie>), action.ReturnType.ClrType);
        }
Example #33
0
        private static IEdmModel GetExplicitEdmModel()
        {
            var modelBuilder = new ODataModelBuilder();

            var enumContry = modelBuilder.EnumType <Country>();

            enumContry.Member(Country.Canada);
            enumContry.Member(Country.China);
            enumContry.Member(Country.India);
            enumContry.Member(Country.Japen);
            enumContry.Member(Country.USA);

            var products = modelBuilder.EntitySet <Product>("Products");

            products.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(ODataTestConstants.DefaultRouteName,
                                                      new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var suppliers = modelBuilder.EntitySet <Supplier>("Suppliers");

            suppliers.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(ODataTestConstants.DefaultRouteName,
                                                      new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var families = modelBuilder.EntitySet <ProductFamily>("ProductFamilies");

            families.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(ODataTestConstants.DefaultRouteName,
                                                      new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var product = products.EntityType;

            product.HasKey(p => p.ID);
            product.Property(p => p.Name);
            product.Property(p => p.ReleaseDate);
            product.Property(p => p.SupportedUntil);

            var address = modelBuilder.ComplexType <Address>();

            address.Property(a => a.City);
            address.Property(a => a.Country);
            address.Property(a => a.State);
            address.Property(a => a.Street);
            address.Property(a => a.ZipCode);

            var supplier = suppliers.EntityType;

            supplier.HasKey(s => s.ID);
            supplier.Property(s => s.Name);
            supplier.CollectionProperty(s => s.Addresses);
            supplier.CollectionProperty(s => s.Tags);
            supplier.EnumProperty(s => s.Country);

            var productFamily = families.EntityType;

            productFamily.HasKey(pf => pf.ID);
            productFamily.Property(pf => pf.Name);
            productFamily.Property(pf => pf.Description);

            // Create relationships and bindings in one go
            products.HasRequiredBinding(p => p.Family, families);
            families.HasManyBinding(pf => pf.Products, products);
            families.HasOptionalBinding(pf => pf.Supplier, suppliers);
            suppliers.HasManyBinding(s => s.ProductFamilies, families);

            // Create navigation Link builders
            products.HasNavigationPropertiesLink(
                product.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(ODataTestConstants.DefaultRouteName,
                                                      new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                        new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            families.HasNavigationPropertiesLink(
                productFamily.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(ODataTestConstants.DefaultRouteName,
                                                      new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                        new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            suppliers.HasNavigationPropertiesLink(
                supplier.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.Link(
                                   ODataTestConstants.DefaultRouteName,
                                   new
                {
                    odataPath = entityContext.Url.CreateODataLink(
                        new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                        new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                        new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            return(modelBuilder.GetEdmModel());
        }
Example #34
0
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
 {
     _ = builder.EntitySet <Building>($"{nameof(Building)}s");
     _ = builder.EntitySet <Unit>($"{nameof(Unit)}s");
 }
Example #35
0
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string routePrefix)
 {
     builder.EntitySet <Article>("Articles");
     builder.EntitySet <Review>("Reviews");
 }
        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);
        }
 public static ODataModelBuilder Add_OrderCustomer_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Order>("Orders").HasRequiredBinding(o => o.Customer, "Customer");
     return(builder);
 }
        private static IEdmModel GetModel()
        {
            var config = RoutingConfigurationFactory.CreateWithTypes(typeof(Customer));
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create(config);

            builder.ContainerName = "C";
            builder.Namespace     = "A.B";
            EntityTypeConfiguration <Customer> customer = builder.EntitySet <Customer>("Customers").EntityType;

            // bound actions
            ActionConfiguration primitive = customer.Action("Primitive");

            primitive.Parameter <int>("Quantity");
            primitive.Parameter <string>("ProductCode");
            primitive.Parameter <Date>("Birthday");
            primitive.Parameter <AColor>("BkgColor");
            primitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration complex = customer.Action("Complex");

            complex.Parameter <int>("Quantity");
            complex.Parameter <MyAddress>("Address");

            ActionConfiguration enumType = customer.Action("Enum");

            enumType.Parameter <AColor>("Color");

            ActionConfiguration primitiveCollection = customer.Action("PrimitiveCollection");

            primitiveCollection.Parameter <string>("Name");
            primitiveCollection.CollectionParameter <int>("Ratings");
            primitiveCollection.CollectionParameter <TimeOfDay>("Time");
            primitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration complexCollection = customer.Action("ComplexCollection");

            complexCollection.Parameter <string>("Name");
            complexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration enumCollection = customer.Action("EnumCollection");

            enumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration entity = customer.Action("Entity");

            entity.Parameter <int>("Id");
            entity.EntityParameter <Customer>("Customer");
            entity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration entityCollection = customer.Action("EntityCollection");

            entityCollection.Parameter <int>("Id");
            entityCollection.CollectionEntityParameter <Customer>("Customers");

            // unbound actions
            ActionConfiguration unboundPrimitive = builder.Action("UnboundPrimitive");

            unboundPrimitive.Parameter <int>("Quantity");
            unboundPrimitive.Parameter <string>("ProductCode");
            unboundPrimitive.Parameter <Date>("Birthday");
            unboundPrimitive.Parameter <AColor>("BkgColor");
            unboundPrimitive.Parameter <AColor?>("InnerColor");

            ActionConfiguration unboundComplex = builder.Action("UnboundComplex");

            unboundComplex.Parameter <int>("Quantity");
            unboundComplex.Parameter <MyAddress>("Address");

            ActionConfiguration unboundEnum = builder.Action("UnboundEnum");

            unboundEnum.Parameter <AColor>("Color");

            ActionConfiguration unboundPrimitiveCollection = builder.Action("UnboundPrimitiveCollection");

            unboundPrimitiveCollection.Parameter <string>("Name");
            unboundPrimitiveCollection.CollectionParameter <int>("Ratings");
            unboundPrimitiveCollection.CollectionParameter <TimeOfDay>("Time");
            unboundPrimitiveCollection.CollectionParameter <AColor?>("Colors");

            ActionConfiguration unboundComplexCollection = builder.Action("UnboundComplexCollection");

            unboundComplexCollection.Parameter <string>("Name");
            unboundComplexCollection.CollectionParameter <MyAddress>("Addresses");

            ActionConfiguration unboundEnumCollection = builder.Action("UnboundEnumCollection");

            unboundEnumCollection.CollectionParameter <AColor>("Colors");

            ActionConfiguration unboundEntity = builder.Action("UnboundEntity");

            unboundEntity.Parameter <int>("Id");
            unboundEntity.EntityParameter <Customer>("Customer").Nullable = false;
            unboundEntity.EntityParameter <Customer>("NullableCustomer");

            ActionConfiguration unboundEntityCollection = builder.Action("UnboundEntityCollection");

            unboundEntityCollection.Parameter <int>("Id");
            unboundEntityCollection.CollectionEntityParameter <Customer>("Customers");

            return(builder.GetEdmModel());
        }
Example #39
0
        private static IEdmModel GetExplicitModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            EntitySetConfiguration <ModelAliasingMetadataCustomer> customers = builder.EntitySet <ModelAliasingMetadataCustomer>("Customers");

            customers.EntityType.HasKey(c => c.Id);
            customers.EntityType.Property(c => c.Name);
            customers.EntityType.ComplexProperty(c => c.BillingAddress);
            customers.EntityType.ComplexProperty(c => c.DefaultShippingAddress);
            customers.EntityType.HasMany(c => c.Orders);

            EntityTypeConfiguration <ModelAliasingMetadataExpressOrder> expressOrder = builder.EntityType <ModelAliasingMetadataExpressOrder>().DerivesFrom <ModelAliasingMetadataOrder>();

            expressOrder.Property(eo => eo.ExpressFee);
            expressOrder.Property(eo => eo.GuaranteedDeliveryDate);

            EntityTypeConfiguration <ModelAliasingMetadataFreeDeliveryOrder> freeDeliveryOrder = builder.EntityType <ModelAliasingMetadataFreeDeliveryOrder>().DerivesFrom <ModelAliasingMetadataOrder>();

            freeDeliveryOrder.Property(fdo => fdo.EstimatedDeliveryDate);

            EntitySetConfiguration <ModelAliasingMetadataOrder> orders = builder.EntitySet <ModelAliasingMetadataOrder>("Orders");

            orders.EntityType.HasKey(o => o.Id);
            orders.EntityType.Property(o => o.PurchaseDate);
            orders.EntityType.ComplexProperty(o => o.ShippingAddress);
            orders.EntityType.HasMany(o => o.Details);
            EntitySetConfiguration <ModelAliasingMetadataOrderLine> ordersLines = builder.EntitySet <ModelAliasingMetadataOrderLine>("OrdersLines");

            ordersLines.EntityType.HasKey(ol => ol.Id);
            ordersLines.EntityType.HasOptional(ol => ol.Item);
            ordersLines.EntityType.Property(ol => ol.Price);
            ordersLines.EntityType.Property(ol => ol.Ammount);
            ComplexTypeConfiguration <ModelAliasingMetadataAddress> address = builder.ComplexType <ModelAliasingMetadataAddress>();

            address.Property(a => a.FirstLine);
            address.Property(a => a.SecondLine);
            address.Property(a => a.ZipCode);
            address.Property(a => a.City);
            address.ComplexProperty(a => a.CountryOrRegion);
            ComplexTypeConfiguration <ModelAliasingMetadataRegion> region = builder.ComplexType <ModelAliasingMetadataRegion>();

            region.Property(r => r.CountryOrRegion);
            region.Property(r => r.State);

            EntitySetConfiguration <ModelAliasingMetadataProduct> products = builder.EntitySet <ModelAliasingMetadataProduct>("Products");

            products.EntityType.HasKey(p => p.Id);
            products.EntityType.Property(p => p.Name);
            products.EntityType.CollectionProperty(p => p.Regions);

            customers.EntityType.Name      = "Customer";
            customers.EntityType.Namespace = "ModelAliasing";
            customers.EntityType.ComplexProperty(c => c.BillingAddress).Name = "FinancialAddress";
            customers.EntityType.Property(c => c.Name).Name  = "ClientName";
            customers.EntityType.HasMany(c => c.Orders).Name = "Purchases";

            orders.EntityType.Name      = "Order";
            orders.EntityType.Namespace = "AliasedNamespace";

            expressOrder.Name      = "ExpressOrder";
            expressOrder.Namespace = "Purchasing";
            expressOrder.Property(eo => eo.ExpressFee).Name = "Fee";

            freeDeliveryOrder.Name      = "FreeOrder";
            freeDeliveryOrder.Namespace = "Purchasing";

            ordersLines.EntityType.Property(ol => ol.Price).Name = "Cost";
            region.Name      = "PoliticalRegion";
            region.Namespace = "Location";

            address.Name      = "Direction";
            address.Namespace = "Location";
            address.ComplexProperty <ModelAliasingMetadataRegion>(c => c.CountryOrRegion).Name = "Reign";
            return(builder.GetEdmModel());
        }
        private static IEdmModel GetExplicitEdmModel()
        {
            var modelBuilder = new ODataModelBuilder();

            var enumContry = modelBuilder.EnumType <CountryOrRegion>();

            enumContry.Member(CountryOrRegion.Canada);
            enumContry.Member(CountryOrRegion.China);
            enumContry.Member(CountryOrRegion.India);
            enumContry.Member(CountryOrRegion.Japen);
            enumContry.Member(CountryOrRegion.USA);

            var products            = modelBuilder.EntitySet <Product>("Products");
            var toiletPaperSupplier = modelBuilder.EntityType <ToiletPaperSupplier>();

            products.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(ODataTestConstants.DefaultRouteName,
                                                                 new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var mainSupplier = modelBuilder.Singleton <Supplier>("MainSupplier");

            var suppliers = modelBuilder.EntitySet <Supplier>("Suppliers").HasDerivedTypeConstraint <ToiletPaperSupplier>();

            mainSupplier.HasDerivedTypeConstraints(typeof(ToiletPaperSupplier));

            suppliers.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(ODataTestConstants.DefaultRouteName,
                                                                 new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var families = modelBuilder.EntitySet <ProductFamily>("ProductFamilies");

            families.HasEditLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(ODataTestConstants.DefaultRouteName,
                                                                 new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null))
                })));
            }, true);

            var product = products.EntityType;

            product.HasKey(p => p.ID);
            product.Property(p => p.Name);
            product.Property(p => p.ReleaseDate);
            product.Property(p => p.SupportedUntil);

            var address = modelBuilder.ComplexType <Address>();

            address.Property(a => a.City);
            address.Property(a => a.CountryOrRegion);
            address.Property(a => a.State);
            address.Property(a => a.Street);
            address.Property(a => a.ZipCode);

            var supplier = suppliers.EntityType;

            supplier.HasKey(s => s.ID);
            supplier.Property(s => s.Name);
            supplier.CollectionProperty(s => s.Addresses);
            supplier.CollectionProperty(s => s.Tags);
            supplier.EnumProperty(s => s.CountryOrRegion);
            supplier.ComplexProperty(s => s.MainAddress).HasDerivedTypeConstraints(typeof(Address));

            var productFamily = families.EntityType;

            productFamily.HasKey(pf => pf.ID);
            productFamily.Property(pf => pf.Name);
            productFamily.Property(pf => pf.Description);

            // Create relationships and bindings in one go
            products.HasRequiredBinding(p => p.Family, families);
            families.HasManyBinding(pf => pf.Products, products);
            families.HasOptionalBinding(pf => pf.Supplier, suppliers).NavigationProperty.HasDerivedTypeConstraint <ToiletPaperSupplier>();
            suppliers.HasManyBinding(s => s.ProductFamilies, families);

            // Create navigation Link builders
            products.HasNavigationPropertiesLink(
                product.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(ODataTestConstants.DefaultRouteName,
                                                                 new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                                                                      new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            families.HasNavigationPropertiesLink(
                productFamily.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(ODataTestConstants.DefaultRouteName,
                                                                 new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                                                                      new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            suppliers.HasNavigationPropertiesLink(
                supplier.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.GetUrlHelper().Link(
                                   ODataTestConstants.DefaultRouteName,
                                   new
                {
                    odataPath = ResourceContextHelper.CreateODataLink(entityContext,
                                                                      new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                                                                      new KeySegment(new[] { new KeyValuePair <string, object>("ID", id) }, entityContext.StructuredType as IEdmEntityType, null),
                                                                      new NavigationPropertySegment(navigationProperty, null))
                })));
            }, true);

            var function = supplier.Function("GetAddress").Returns <Address>().HasDerivedTypeConstraintForReturnType <Address>();

            function.ReturnTypeConstraints.Location = Microsoft.OData.Edm.Csdl.EdmVocabularyAnnotationSerializationLocation.OutOfLine;
            function.Parameter <int>("value");

            var action = modelBuilder.Action("GetAddress").Returns <Address>().HasDerivedTypeConstraintsForReturnType(typeof(Address));

            action.Parameter <Supplier>("supplier").HasDerivedTypeConstraint <ToiletPaperSupplier>();
            action.ReturnTypeConstraints.Location = Microsoft.OData.Edm.Csdl.EdmVocabularyAnnotationSerializationLocation.OutOfLine;

            return(modelBuilder.GetEdmModel());
        }
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string routePrefix)
 {
     builder.EntitySet <Person>("Persons");
 }
Example #42
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());
        }
Example #43
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.InternalUrlHelper.CreateODataLink(new EntitySetSegment(
                                                                                                        context.EntitySetBase as IEdmEntitySet))));
                people.HasIdLink(context =>
                {
                    var keys = new[] { new KeyValuePair <string, object>("PerId", context.GetPropertyValue("PerId")) };
                    return(new Uri(context.InternalUrlHelper.CreateODataLink(
                                       new EntitySetSegment(context.NavigationSource as IEdmEntitySet),
                                       new KeySegment(keys, context.StructuredType as IEdmEntityType, context.NavigationSource))));
                },
                                 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 a function to test namespace configuration
                var getNSFunction = model.Function("GetNS");
                getNSFunction.Returns <int>();
                getNSFunction.Namespace = "CustomizeNamepace";

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

                _model = model.GetEdmModel();
            }

            return(_model);
        }
        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();
        }
        public void CreateEdmModel_WithSingletonAndEntitySet_AndEntitySetBindingToSingleton()
        {
            // Arrange
            var builder = new ODataModelBuilder()
                .Add_Company_EntityType()
                .Add_Employee_EntityType()
                .Add_CompanyEmployees_Relationship();

            // EntitySet -> Singleton
            builder.EntitySet<Company>("Companies").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 entitySet = container.FindEntitySet("Companies");
            Assert.NotNull(entitySet);

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

            var ceo = entitySet.NavigationPropertyBindings.FirstOrDefault(nt => nt.NavigationProperty.Name == "CEO");
            Assert.NotNull(ceo);
            Assert.Same(singleton, ceo.Target);
            Assert.Equal("Boss", ceo.Target.Name);
        }
 public static ODataModelBuilder Add_Orders_EntitySet(this ODataModelBuilder builder)
 {
     builder.EntitySet <Order>("Orders");
     return(builder);
 }
        private void BuildControllerOperations <TDto>(ODataModelBuilder odataModelBuilder, TypeInfo apiController)
            where TDto : class
        {
            string controllerName = GetControllerName(apiController);
            EntitySetConfiguration <TDto> entitySet = odataModelBuilder.EntitySet <TDto>(controllerName);

            foreach (MethodInfo method in apiController.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly))
            {
                IActionHttpMethodProvider actionHttpMethodProvider =
                    method.GetCustomAttributes().OfType <FunctionAttribute>().Cast <IActionHttpMethodProvider>()
                    .Union(method.GetCustomAttributes().OfType <ActionAttribute>().Cast <IActionHttpMethodProvider>())
                    .ExtendedSingleOrDefault($"Finding ${nameof(IActionHttpMethodProvider)} attribute in {method.Name}");

                if (actionHttpMethodProvider != null)
                {
                    bool isFunction = actionHttpMethodProvider is FunctionAttribute;
                    bool isAction   = actionHttpMethodProvider is ActionAttribute;

                    if (!isFunction && !isAction)
                    {
                        continue;
                    }

                    List <DefaultAutoODataModelBuilderParameterInfo> operationParameters = new List <DefaultAutoODataModelBuilderParameterInfo>();

                    if (isFunction)
                    {
                        foreach (ParameterInfo parameter in method.GetParameters())
                        {
                            if (parameter.ParameterType.GetTypeInfo() == typeof(CancellationToken).GetTypeInfo() || typeof(ODataQueryOptions).IsAssignableFrom(parameter.ParameterType.GetTypeInfo()))
                            {
                                continue;
                            }
                            operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                Name = parameter.Name, Type = parameter.ParameterType.GetTypeInfo()
                            });
                        }
                    }
                    else if (isAction)
                    {
                        ParameterInfo parameter = method
                                                  .GetParameters()
                                                  .ExtendedSingleOrDefault($"Finding parameter of {method.Name}", p => p.ParameterType.GetTypeInfo() != typeof(CancellationToken).GetTypeInfo() && !typeof(ODataQueryOptions).IsAssignableFrom(p.ParameterType.GetTypeInfo()));

                        if (parameter != null)
                        {
                            foreach (PropertyInfo prop in parameter.ParameterType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                            {
                                operationParameters.Add(new DefaultAutoODataModelBuilderParameterInfo {
                                    Name = prop.Name, Type = prop.PropertyType.GetTypeInfo()
                                });
                            }
                        }
                    }

                    OperationConfiguration operationConfiguration = null;

                    if (isAction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Action(method.Name);
                    }
                    else if (isFunction)
                    {
                        operationConfiguration = entitySet.EntityType.Collection.Function(method.Name);
                    }

                    foreach (DefaultAutoODataModelBuilderParameterInfo operationParameter in operationParameters)
                    {
                        TypeInfo parameterType = operationParameter.Type;

                        if (operationParameter.Type.GetTypeInfo() != typeof(string).GetTypeInfo() &&
                            typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(operationParameter.Type))
                        {
                            if (parameterType.IsArray)
                            {
                                throw new InvalidOperationException($"Use IEnumerable<{parameterType.GetElementType().GetTypeInfo().Name}> instead of {parameterType.GetElementType().GetTypeInfo().Name}[] for parameter {operationParameter.Name} of {operationParameter.Name} in {controllerName} controller");
                            }

                            if (parameterType.IsGenericType)
                            {
                                parameterType = parameterType.GetGenericArguments().ExtendedSingle($"Finding parameter type from generic arguments of {parameterType.Name}").GetTypeInfo();
                            }

                            ParameterConfiguration parameter = (ParameterConfiguration)_collectionParameterMethodInfo
                                                               .MakeGenericMethod(parameterType)
                                                               .Invoke(operationConfiguration, new object[] { operationParameter.Name });
                            parameter.Nullable = operationParameter.IsOptional;
                        }
                        else
                        {
                            operationConfiguration.Parameter(parameterType, operationParameter.Name).Nullable = operationParameter.IsOptional;
                        }
                    }

                    TypeInfo type = method.ReturnType.GetTypeInfo();

                    if (type.Name != "Void" && type.Name != typeof(Task).GetTypeInfo().Name)
                    {
                        operationConfiguration.ReturnNullable = false;

                        bool isCollection = false;

                        if (typeof(Task).GetTypeInfo().IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                        }

                        if (typeof(SingleResult).GetTypeInfo().IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                        }

                        if (typeof(string) != type && typeof(IEnumerable).IsAssignableFrom(type))
                        {
                            if (type.IsGenericType)
                            {
                                type = type.GetGenericArguments().ExtendedSingle($"Finding Return type of {method.Name}").GetTypeInfo();
                            }
                            else if (type.IsArray)
                            {
                                type = type.GetElementType().GetTypeInfo();
                            }
                            isCollection = true;
                        }

                        if (DtoMetadataWorkspace.Current.IsDto(type))
                        {
                            type = DtoMetadataWorkspace.Current.GetFinalDtoType(type);

                            if (isCollection == true)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                                else
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsCollectionFromEntitySet <TDto>(controllerName);
                                }
                            }
                            else
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).ReturnsFromEntitySet <TDto>(controllerName);
                                }
                            }
                        }
                        else
                        {
                            if (isCollection == false)
                            {
                                if (isAction)
                                {
                                    ((ActionConfiguration)operationConfiguration).Returns(type);
                                }
                                else if (isFunction)
                                {
                                    ((FunctionConfiguration)operationConfiguration).Returns(type);
                                }
                            }
                            else
                            {
                                operationConfiguration.GetType()
                                .GetTypeInfo()
                                .GetMethod("ReturnsCollection")
                                .MakeGenericMethod(type)
                                .Invoke(operationConfiguration, Array.Empty <object>());
                            }
                        }
                    }
                    else
                    {
                        if (isFunction)
                        {
                            throw new InvalidOperationException($"Function {method.Name} in {apiController.Name} must have a return type, use action instead");
                        }

                        operationConfiguration.ReturnNullable = true;
                    }
                }
            }
        }
 public static ODataModelBuilder Add_CustomerOrders_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Customer>("Customers").HasManyBinding(c => c.Orders, "Orders");
     return(builder);
 }
Example #49
0
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
 {
     _ = builder.EntitySet <Item>($"{nameof(Item)}s");
 }
 public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string?routePrefix)
 {
     builder.EntitySet <Pong>("Pongs").EntityType
     .HasKey(_ => _.Id)
     .Select().Count();
 }
        /// <summary>
        /// Generates a model explicitly.
        /// </summary>
        /// <returns></returns>
        static IEdmModel GetExplicitEdmModel()
        {
            ODataModelBuilder modelBuilder = new ODataModelBuilder();

            var products = modelBuilder.EntitySet <Product>("Products");

            products.HasEditLink(
                entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(entityContext.Url.ODataLink(
                           new EntitySetPathSegment(entityContext.EntitySet.Name),
                           new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3))));
            },
                followsConventions: true);

            var suppliers = modelBuilder.EntitySet <Supplier>("Suppliers");

            suppliers.HasEditLink(
                entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(entityContext.Url.ODataLink(
                           new EntitySetPathSegment(entityContext.EntitySet.Name),
                           new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3))));
            },
                followsConventions: true);

            var families = modelBuilder.EntitySet <ProductFamily>("ProductFamilies");

            families.HasEditLink(
                entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(entityContext.Url.ODataLink(
                           new EntitySetPathSegment(entityContext.EntitySet.Name),
                           new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3))));
            },
                followsConventions: true);

            var product = products.EntityType;

            product.HasKey(p => p.ID);
            product.Property(p => p.Name);
            product.Property(p => p.ReleaseDate);
            product.Property(p => p.SupportedUntil);

            modelBuilder.Entity <RatedProduct>().DerivesFrom <Product>().Property(rp => rp.Rating);

            var address = modelBuilder.ComplexType <Address>();

            address.Property(a => a.City);
            address.Property(a => a.Country);
            address.Property(a => a.State);
            address.Property(a => a.Street);
            address.Property(a => a.ZipCode);

            var supplier = suppliers.EntityType;

            supplier.HasKey(s => s.ID);
            supplier.Property(s => s.Name);
            supplier.ComplexProperty(s => s.Address);

            var productFamily = families.EntityType;

            productFamily.HasKey(pf => pf.ID);
            productFamily.Property(pf => pf.Name);
            productFamily.Property(pf => pf.Description);

            // Create relationships and bindings in one go
            products.HasRequiredBinding(p => p.Family, families);
            families.HasManyBinding(pf => pf.Products, products);
            families.HasOptionalBinding(pf => pf.Supplier, suppliers);
            suppliers.HasManyBinding(s => s.ProductFamilies, families);

            // Create navigation Link builders
            products.HasNavigationPropertiesLink(
                product.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.ODataLink(
                                   new EntitySetPathSegment(entityContext.EntitySet.Name),
                                   new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3)),
                                   new NavigationPathSegment(navigationProperty.Name))));
            },
                followsConventions: true);

            families.HasNavigationPropertiesLink(
                productFamily.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.ODataLink(
                                   new EntitySetPathSegment(entityContext.EntitySet.Name),
                                   new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3)),
                                   new NavigationPathSegment(navigationProperty.Name))));
            },
                followsConventions: true);

            suppliers.HasNavigationPropertiesLink(
                supplier.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("ID", out id);
                return(new Uri(entityContext.Url.ODataLink(
                                   new EntitySetPathSegment(entityContext.EntitySet.Name),
                                   new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V3)),
                                   new NavigationPathSegment(navigationProperty.Name))));
            },
                followsConventions: true);

            ActionConfiguration createProduct = product.Action("CreateProduct");

            createProduct.Parameter <string>("Name");
            createProduct.Returns <int>();

            return(modelBuilder.GetEdmModel());
        }
Example #52
0
        public static IEdmModel GetExplicitModel(bool foreignKey)
        {
            ODataModelBuilder builder = new ODataModelBuilder();
            var customer = builder.EntityType <ForeignKeyCustomer>();

            customer.HasKey(c => c.Id);
            customer.Property(c => c.Name);
            customer.HasMany(c => c.Orders);

            var order = builder.EntityType <ForeignKeyOrder>();

            order.HasKey(o => o.OrderId);
            order.Property(o => o.OrderName);
            order.Property(o => o.CustomerId);

            EntitySetConfiguration <ForeignKeyCustomer> customers;
            EntitySetConfiguration <ForeignKeyOrder>    orders;

            if (foreignKey)
            {
                order.HasOptional(o => o.Customer, (o, c) => o.CustomerId == c.Id).CascadeOnDelete(cascade: true);

                customers = builder.EntitySet <ForeignKeyCustomer>("ForeignKeyCustomers");
                orders    = builder.EntitySet <ForeignKeyOrder>("ForeignKeyOrders");
                customers.HasManyBinding(c => c.Orders, "ForeignKeyOrders");
                orders.HasOptionalBinding(o => o.Customer, "ForeignKeyCustomers");
            }
            else
            {
                order.HasOptional(o => o.Customer);

                customers = builder.EntitySet <ForeignKeyCustomer>("ForeignKeyCustomersNoCascade");
                orders    = builder.EntitySet <ForeignKeyOrder>("ForeignKeyOrdersNoCascade");
                customers.HasManyBinding(c => c.Orders, "ForeignKeyOrdersNoCascade");
                orders.HasOptionalBinding(o => o.Customer, "ForeignKeyCustomersNoCascade");
            }

            customers.HasIdLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                string uri = entityContext.Url.CreateODataLink(
                    new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                    new KeySegment(new[] { new KeyValuePair <string, object>("Id", id) }, entityContext.StructuredType as IEdmEntityType, null));
                return(new Uri(uri));
            }, true);

            orders.HasIdLink(entityContext =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("OrderId", out id);
                string uri = entityContext.Url.CreateODataLink(
                    new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                    new KeySegment(new[] { new KeyValuePair <string, object>("OrderId", id) }, entityContext.StructuredType as IEdmEntityType, null));
                return(new Uri(uri));
            }, true);

            // Create navigation Link builders
            customers.HasNavigationPropertiesLink(
                customer.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                string uri = entityContext.Url.CreateODataLink(
                    new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                    new KeySegment(new[] { new KeyValuePair <string, object>("Id", id) }, entityContext.StructuredType as IEdmEntityType, null),
                    new NavigationPropertySegment(navigationProperty, null));
                return(new Uri(uri));
            }, true);

            orders.HasNavigationPropertiesLink(
                order.NavigationProperties,
                (entityContext, navigationProperty) =>
            {
                object id;
                entityContext.EdmObject.TryGetPropertyValue("OrderId", out id);
                string uri = entityContext.Url.CreateODataLink(
                    new EntitySetSegment(entityContext.NavigationSource as IEdmEntitySet),
                    new KeySegment(new[] { new KeyValuePair <string, object>("OrderId", id) }, entityContext.StructuredType as IEdmEntityType, null),
                    new NavigationPropertySegment(navigationProperty, null));
                return(new Uri(uri));
            }, true);

            BuildAction(builder);

            return(builder.GetEdmModel());
        }
        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;
        }
        public void CanBuildBoundOperationCacheForIEdmModel()
        {
            // 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.EntityType <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);
            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
            BindableOperationFinder annotation = new BindableOperationFinder(model);

            IEdmAction[] movieActions = annotation.FindOperations(movieType)
                                        .OfType <IEdmAction>()
                                        .ToArray();
            IEdmAction[] customerActions = annotation.FindOperations(customerType)
                                           .OfType <IEdmAction>()
                                           .ToArray();
            IEdmAction[] blockBusterActions = annotation.FindOperations(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"));
        }
Example #55
0
        private static IEdmModel GetActionsModel(WebRouteConfiguration configuration)
        {
            ODataModelBuilder builder         = configuration.CreateConventionModelBuilder();
            var baseEntitySet                 = builder.EntitySet <BaseEntity>("BaseEntity");
            var alwaysAvailableActionBaseType = baseEntitySet.EntityType.Action("AlwaysAvailableActionBaseType");
            var transientActionBaseType       = baseEntitySet.EntityType.Action("TransientActionBaseType");

            Func <ResourceContext, Uri> transientActionBaseTypeLinkFactory = eic =>
            {
                IEdmEntityType baseType = eic.EdmModel.FindType(typeof(BaseEntity).FullName) as IEdmEntityType;
                object         id;
                eic.EdmObject.TryGetPropertyValue("Id", out id);
                if (!eic.StructuredType.IsOrInheritsFrom(baseType) || (int)id % 2 == 1)
                {
                    return(null);
                }
                else
                {
                    // find the action
                    var action = eic.EdmModel.SchemaElements
                                 .Where(elem => elem.Name == "TransientActionBaseType")
                                 .Cast <EdmAction>()
                                 .FirstOrDefault();

                    var segments = new List <ODataPathSegment>();
                    segments.Add(new EntitySetSegment(eic.NavigationSource as IEdmEntitySet));
                    segments.Add(new KeySegment(new[] { new KeyValuePair <string, object>("Id", id) }, eic.StructuredType as IEdmEntityType, null));
                    var    pathHandler = eic.Request.GetPathHandler();
                    string link        = ResourceContextHelper.CreateODataLink(eic, "Actions", pathHandler, segments);
                    link += "/" + action.FullName();
                    return(new Uri(link));
                }
            };

            transientActionBaseType.HasActionLink(transientActionBaseTypeLinkFactory, true);
            var derivedEntityType = builder.EntityType <DerivedEntity>().DerivesFrom <BaseEntity>();
            var alwaysAvailableActionDerivedType = derivedEntityType.Action("AlwaysAvailableActionDerivedType");
            var transientActionDerivedType       = derivedEntityType.Action("TransientActionDerivedType");
            Func <ResourceContext, Uri> transientActionDerivedTypeLinkFactory = eic =>
            {
                IEdmEntityType derivedType = eic.EdmModel.FindType(typeof(DerivedEntity).FullName) as IEdmEntityType;
                object         id;
                eic.EdmObject.TryGetPropertyValue("Id", out id);
                if (!eic.StructuredType.IsOrInheritsFrom(derivedType) || (int)id % 2 == 1)
                {
                    return(null);
                }
                else
                {
                    // find the action
                    var action = eic.EdmModel.SchemaElements
                                 .Where(elem => elem.Name == "TransientActionDerivedType")
                                 .Cast <EdmAction>()
                                 .FirstOrDefault();

                    var segments = new List <ODataPathSegment>();
                    segments.Add(new EntitySetSegment(eic.NavigationSource as IEdmEntitySet));
                    segments.Add(new KeySegment(new[] { new KeyValuePair <string, object>("Id", id) }, eic.StructuredType as IEdmEntityType, null));
                    segments.Add(new TypeSegment(derivedType, null));
                    // bug 1985: Make the internal constructor as public in BoundActionPathSegment
                    //segments.Add(new BoundActionPathSegment(action));
                    var    pathHandler = eic.Request.GetPathHandler();
                    string link        = ResourceContextHelper.CreateODataLink(eic, "Actions", pathHandler, segments);
                    link += "/" + action.FullName();
                    return(new Uri(link));
                }
            };

            transientActionDerivedType.HasActionLink(transientActionDerivedTypeLinkFactory, true);
            return(builder.GetEdmModel());
        }
        public void CanBuildOperationBoundToCollectionCacheForIEdmModel()
        {
            // 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.EntityType <Blockbuster>().DerivesFrom <Movie>();
            EntityTypeConfiguration movieConfiguration        = builder.StructuralTypes.OfType <EntityTypeConfiguration>().Single(t => t.Name == "Movie");

            // build actions that are bindable to the collection of entity
            customer.Collection.Action("CollectionCustomerActionInCache1");
            customer.Collection.Action("CollectionCustomerActionInCache2");
            movie.Collection.Action("CollectionMovieActionInCache3");

            ActionConfiguration         movieActionIncache4     = builder.Action("CollectionMovieActionInCache4");
            CollectionTypeConfiguration collectionConfiguration = new CollectionTypeConfiguration(movieConfiguration, typeof(Movie));

            movieActionIncache4.SetBindingParameter("bindingParameter", collectionConfiguration);

            blockBuster.Collection.Action("CollectionBlockbusterActionInCache5");

            // build functions that are bindable to the collection of entity
            customer.Collection.Function("CollectionCustomerFunctionInCache1").Returns <int>();
            customer.Collection.Function("CollectionCustomerFunctionInCache2").Returns <int>();
            movie.Collection.Function("CollectionMovieFunctionInCache3").Returns <int>();
            blockBuster.Collection.Function("CollectionBlockbusterFunctionInCache5").Returns <int>();

            // build actions that are either: bindable to an entity, have no parameter, have only complex parameter
            customer.Action("CustomersActionNotInCache1");
            customer.Function("CustomersFunctionNotInCache1").Returns <int>();
            movie.Action("MoviesActionNotInCache2");
            builder.Action("NoParametersNotInCache3");

            ActionConfiguration addressParameterNotInCache4 = builder.Action("AddressParameterNotInCache4");

            addressParameterNotInCache4.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
            BindableOperationFinder annotation = new BindableOperationFinder(model);
            var movieOperations       = annotation.FindOperationsBoundToCollection(movieType).ToArray();
            var customerOperations    = annotation.FindOperationsBoundToCollection(customerType).ToArray();
            var blockBusterOperations = annotation.FindOperationsBoundToCollection(blockBusterType).ToArray();

            // Assert
            Assert.Equal(3, movieOperations.Length);
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieActionInCache3"));
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieActionInCache4"));
            Assert.Single(movieOperations.Where(a => a.Name == "CollectionMovieFunctionInCache3"));

            Assert.Equal(4, customerOperations.Length);
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerActionInCache1"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerActionInCache2"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerFunctionInCache1"));
            Assert.Single(customerOperations.Where(a => a.Name == "CollectionCustomerFunctionInCache2"));

            Assert.Equal(5, blockBusterOperations.Length);
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionBlockbusterActionInCache5"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionBlockbusterFunctionInCache5"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieActionInCache3"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieActionInCache4"));
            Assert.Single(blockBusterOperations.Where(a => a.Name == "CollectionMovieFunctionInCache3"));
        }
        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 #58
0
 private static void ConfigureV1(ODataModelBuilder builder)
 {
     builder.Namespace = "Haipa";
     builder.EntitySet <Client>("Clients");
     builder.EntityType <Client>().Name = "Client";
 }
        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.");
        }
Example #60
0
        private static IEdmModel GetEdmModel()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

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

            builder
            .EntityType <Motorcycle>()
            .DerivesFrom <Vehicle>()
            .Property(m => m.CanDoAWheelie);

            var vehConfig = builder
                            .EntityType <Motorcycle>()
                            .DerivesFrom <Vehicle>();

            vehConfig.ComplexProperty(m => m.MyEngine);
            vehConfig.ComplexProperty(m => m.MyV4Engine);
            builder.ComplexType <Engine>().ComplexProperty(m => m.Transmission).IsOptional();

            builder.ComplexType <Engine>().Property(m => m.Hp);
            builder.ComplexType <Transmission>().Property(m => m.Gears);
            builder.ComplexType <Automatic>().DerivesFrom <Transmission>();
            builder.ComplexType <Manual>().DerivesFrom <Transmission>();

            builder.ComplexType <V2>().DerivesFrom <Engine>();
            builder.ComplexType <V4>().DerivesFrom <Engine>();
            builder.ComplexType <V41>().DerivesFrom <V4>();
            builder.ComplexType <V41>().Property(m => m.MakeName);
            builder.ComplexType <V42>().Property(m => m.Model);
            builder.ComplexType <V42>().DerivesFrom <V4>();
            builder.ComplexType <V422>().DerivesFrom <V42>();

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

            builder.EntitySet <Vehicle>("vehicles").HasIdLink(
                (v) => new Uri("http://localhost/vehicles/" + v.GetPropertyValue("Name")), followsConventions: false);
            builder.EntitySet <Motorcycle>("motorcycles").HasIdLink(
                (m) => new Uri("http://localhost/motorcycles/" + m.GetPropertyValue("Name")), followsConventions: false);
            builder.EntitySet <Car>("cars");

            builder
            .Action("GetCarAsVehicle")
            .ReturnsFromEntitySet <Vehicle>("vehicles");
            builder
            .Action("GetMotorcycleAsVehicle")
            .ReturnsFromEntitySet <Vehicle>("vehicles");
            builder
            .Action("GetSportBikeAsVehicle")
            .ReturnsFromEntitySet <Vehicle>("vehicles");
            builder
            .Action("GetVehicles")
            .ReturnsFromEntitySet <Vehicle>("vehicles");

            builder
            .Action("PatchMotorcycle_When_Expecting_Motorcycle")
            .ReturnsFromEntitySet <Motorcycle>("motorcycles");
            builder
            .Action("PatchMotorcycle_When_Expecting_Motorcycle_DerivedEngine")
            .ReturnsFromEntitySet <Motorcycle>("motorcycles");

            builder
            .Action("PatchMotorcycle_When_Expecting_Motorcycle_DerivedEngine2")
            .ReturnsFromEntitySet <Motorcycle>("motorcycles");

            builder
            .Action("PatchMotorcycle_When_Expecting_Motorcycle_DerivedEngine42")
            .ReturnsFromEntitySet <Motorcycle>("motorcycles");

            builder
            .Action("PostMotorcycle_When_Expecting_Motorcycle")
            .ReturnsFromEntitySet <Motorcycle>("motorcycles");
            builder
            .Action("PatchMotorcycle_When_Expecting_Vehicle")
            .ReturnsFromEntitySet <Vehicle>("vehicles");
            builder
            .Action("PostMotorcycle_When_Expecting_Vehicle")
            .ReturnsFromEntitySet <Vehicle>("vehicles");
            builder
            .Action("PostMotorcycle_When_Expecting_Car")
            .ReturnsFromEntitySet <Car>("cars");
            builder
            .Action("PatchMotorcycle_When_Expecting_Car")
            .ReturnsFromEntitySet <Car>("cars");

            return(builder.GetEdmModel());
        }