private static NavigationSourceConfiguration GetDefaultNavigationSource(EntityTypeConfiguration targetEntityType,
            ODataModelBuilder model, bool isSingleton)
        {
            if (targetEntityType == null)
            {
                return null;
            }

            NavigationSourceConfiguration[] matchingNavigationSources = null;
            if (isSingleton)
            {
                matchingNavigationSources = model.Singletons.Where(e => e.EntityType == targetEntityType).ToArray();
            }
            else
            {
                matchingNavigationSources = model.EntitySets.Where(e => e.EntityType == targetEntityType).ToArray();
            }

            if (matchingNavigationSources.Length > 1)
            {
                return null;
            }
            else if (matchingNavigationSources.Length == 1)
            {
                return matchingNavigationSources[0];
            }
            else
            {
                // default navigation source is the same as the default navigation source for the base type.
                return GetDefaultNavigationSource(targetEntityType.BaseType as EntityTypeConfiguration,
                    model, isSingleton);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EnumTypeConfiguration"/> class.
        /// </summary>
        public EnumTypeConfiguration(ODataModelBuilder builder, Type clrType)
        {
            if (builder == null)
            {
                throw Error.ArgumentNull("builder");
            }
            if (clrType == null)
            {
                throw Error.ArgumentNull("clrType");
            }

            if (!clrType.IsEnum)
            {
                throw Error.Argument("clrType", SRResources.TypeCannotBeEnum, clrType.FullName);
            }

            ClrType = clrType;
            IsFlags = clrType.GetCustomAttributes(typeof(FlagsAttribute), false).Any();
            UnderlyingType = Enum.GetUnderlyingType(clrType);
            ModelBuilder = builder;
            _name = clrType.EdmName();
            _namespace = clrType.Namespace ?? DefaultNamespace;
            ExplicitMembers = new Dictionary<Enum, EnumMemberConfiguration>();
            RemovedMembers = new List<Enum>();
        }
        public void ConstructorEmptyRawValueThrows()
        {
            var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();

            Assert.Throws<ArgumentException>(() =>
                new OrderByQueryOption(string.Empty, new ODataQueryContext(model, typeof(Customer))));
        }
        public void AssociationSetDiscoveryConvention_AddsBindingForBaseAndDerivedNavigationProperties()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            EntityTypeConfiguration vehicle = builder.AddEntity(typeof(Vehicle));

            EntityTypeConfiguration car = builder.AddEntity(typeof(Car)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration carNavigationProperty = car.AddNavigationProperty(typeof(Car).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            EntityTypeConfiguration motorcycle = builder.AddEntity(typeof(Motorcycle)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration motorcycleNavigationProperty = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            EntityTypeConfiguration manufacturer = builder.AddEntity(typeof(Manufacturer));
            EntityTypeConfiguration motorcycleManufacturer = builder.AddEntity(typeof(MotorcycleManufacturer)).DerivesFrom(manufacturer);
            EntityTypeConfiguration carManufacturer = builder.AddEntity(typeof(CarManufacturer)).DerivesFrom(manufacturer);

            EntitySetConfiguration manufacturers = builder.AddEntitySet("manufacturers", manufacturer);


            Mock<EntitySetConfiguration> entitySet = new Mock<EntitySetConfiguration>(MockBehavior.Strict);
            entitySet.Setup(v => v.EntityType).Returns(vehicle);
            entitySet.Setup(v => v.AddBinding(motorcycleNavigationProperty, manufacturers)).Returns<NavigationPropertyConfiguration>(null);
            entitySet.Setup(v => v.AddBinding(carNavigationProperty, manufacturers)).Returns<NavigationPropertyConfiguration>(null);

            // Act
            _convention.Apply(entitySet.Object, builder);

            // Assert
            entitySet.VerifyAll();
        }
        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();
        }
Beispiel #6
0
        public void CreateEnumTypeWithFlags()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var color = builder.EnumType<Color>();
            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);

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

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

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

            Assert.NotNull(redMember);
            Assert.NotNull(greenMember);
            Assert.NotNull(blueMember);
        }
        protected NavigationSourceConfiguration(ODataModelBuilder modelBuilder, EntityTypeConfiguration entityType, string name)
        {
            if (modelBuilder == null)
            {
                throw Error.ArgumentNull("modelBuilder");
            }

            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            if (String.IsNullOrEmpty(name))
            {
                throw Error.ArgumentNullOrEmpty("name");
            }

            _modelBuilder = modelBuilder;
            Name = name;
            EntityType = entityType;
            ClrType = entityType.ClrType;
            _url = Name;

            _editLinkBuilder = null;
            _readLinkBuilder = null;
            _navigationPropertyLinkBuilders = new Dictionary<NavigationPropertyConfiguration, NavigationLinkBuilder>();
            _navigationPropertyBindings = new Dictionary<NavigationPropertyConfiguration, NavigationPropertyBindingConfiguration>();
        }
 protected StructuralTypeConfiguration(ODataModelBuilder modelBuilder, Type clrType)
 {
     ClrType = clrType;
     ModelBuilder = modelBuilder;
     ExplicitProperties = new Dictionary<PropertyInfo, PropertyConfiguration>();
     IgnoredProperties = new List<PropertyInfo>();
 }
        public void Apply(ProcedureConfiguration configuration, ODataModelBuilder model)
        {
            FunctionConfiguration function = configuration as FunctionConfiguration;

            if (function == null || !function.IsBindable)
            {
                return;
            }

            // You only need to create links for bindable functions that bind to a single entity.
            if (function.BindingParameter.TypeConfiguration.Kind == EdmTypeKind.Entity && function.GetFunctionLink() == null)
            {
                string bindingParamterType = function.BindingParameter.TypeConfiguration.FullName;

                function.HasFunctionLink(entityContext => 
                    entityContext.GenerateFunctionLink(bindingParamterType, function.FullyQualifiedName, function.Parameters.Select(p => p.Name)), 
                    followsConventions: true);
            }
            else if (function.BindingParameter.TypeConfiguration.Kind == EdmTypeKind.Collection && function.GetFeedFunctionLink() == null)
            {
                if (((CollectionTypeConfiguration)function.BindingParameter.TypeConfiguration).ElementType.Kind ==
                    EdmTypeKind.Entity)
                {
                    string bindingParamterType = function.BindingParameter.TypeConfiguration.FullName;
                    function.HasFeedFunctionLink(
                        feedContext =>
                            feedContext.GenerateFunctionLink(bindingParamterType, function.FullyQualifiedName, function.Parameters.Select(p => p.Name)),
                        followsConventions: true);
                }
            }
        }
        private static Dictionary<string, EdmEntitySet> AddEntitySets(this EdmModel model, ODataModelBuilder builder, EdmEntityContainer container, Dictionary<Type, IEdmStructuredType> edmTypeMap)
        {
            IEnumerable<EntitySetConfiguration> configurations = builder.EntitySets;

            // build the entitysets and their annotations
            IEnumerable<Tuple<EdmEntitySet, EntitySetConfiguration>> entitySets = AddEntitySets(configurations, container, edmTypeMap);
            var entitySetAndAnnotations = entitySets.Select(e => new
            {
                EntitySet = e.Item1,
                Configuration = e.Item2,
                Annotations = new
                {
                    LinkBuilder = new EntitySetLinkBuilderAnnotation(e.Item2),
                    Url = new EntitySetUrlAnnotation { Url = e.Item2.GetUrl() }
                }
            }).ToArray();

            // index the entitySets by name
            Dictionary<string, EdmEntitySet> edmEntitySetMap = entitySetAndAnnotations.ToDictionary(e => e.EntitySet.Name, e => e.EntitySet);

            // apply the annotations
            foreach (var iter in entitySetAndAnnotations)
            {
                EdmEntitySet entitySet = iter.EntitySet;
                model.SetAnnotationValue<EntitySetUrlAnnotation>(entitySet, iter.Annotations.Url);
                model.SetAnnotationValue<IEntitySetLinkBuilder>(entitySet, iter.Annotations.LinkBuilder);

                AddNavigationBindings(iter.Configuration, iter.EntitySet, iter.Annotations.LinkBuilder, builder, edmTypeMap, edmEntitySetMap);
            }
            return edmEntitySetMap;
        }
Beispiel #11
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 void ConstructorNullRawValueThrows()
        {
            var model = new ODataModelBuilder().Add_Customer_EntityType().Add_Customers_EntitySet().GetEdmModel();

            Assert.Throws<ArgumentException>(() =>
                new SkipQueryOption(null, new ODataQueryContext(model, typeof(Customer), "Customers")));
        }
        public static IEdmModel BuildEdmModel(ODataModelBuilder builder)
        {
            if (builder == null)
            {
                throw Error.ArgumentNull("builder");
            }

            EdmModel model = new EdmModel();
            EdmEntityContainer container = new EdmEntityContainer(builder.Namespace, builder.ContainerName);

            // add types and sets, building an index on the way.
            Dictionary<Type, IEdmStructuredType> edmTypeMap = model.AddTypes(builder.StructuralTypes);
            Dictionary<string, EdmEntitySet> edmEntitySetMap = model.AddEntitySets(builder, container, edmTypeMap);

            // add procedures
            model.AddProcedures(builder.Procedures, container, edmTypeMap, edmEntitySetMap);

            // finish up
            model.AddElement(container);

            // build the map from IEdmEntityType to IEdmFunctionImport
            model.SetAnnotationValue<BindableProcedureFinder>(model, new BindableProcedureFinder(model));

            return model;
        }
        public void CanCreateEntityWithCollectionProperties()
        {
            var builder = new ODataModelBuilder();
            var customer = builder.Entity<Customer>();
            customer.HasKey(c => c.CustomerId);
            customer.CollectionProperty(c => c.Aliases);
            customer.CollectionProperty(c => c.Addresses);


            var aliasesProperty = customer.Properties.OfType<CollectionPropertyConfiguration>().SingleOrDefault(p => p.Name == "Aliases");
            var addressesProperty = customer.Properties.OfType<CollectionPropertyConfiguration>().SingleOrDefault(p => p.Name == "Addresses");

            Assert.Equal(3, customer.Properties.Count());
            Assert.Equal(2, customer.Properties.OfType<CollectionPropertyConfiguration>().Count());
            Assert.NotNull(aliasesProperty);
            Assert.Equal(typeof(string), aliasesProperty.ElementType);
            Assert.NotNull(addressesProperty);
            Assert.Equal(typeof(Address), addressesProperty.ElementType);

            Assert.Equal(2, builder.StructuralTypes.Count());
            var addressType = builder.StructuralTypes.Skip(1).FirstOrDefault();
            Assert.NotNull(addressType);
            Assert.Equal(EdmTypeKind.Complex, addressType.Kind);
            Assert.Equal(typeof(Address).FullName, addressType.FullName);

            var model = builder.GetServiceModel();
            var edmCustomerType = model.FindType(typeof(Customer).FullName) as IEdmEntityType;
            var edmAddressType = model.FindType(typeof(Address).FullName) as IEdmComplexType;
        }
        public void CanCreateFunctionWithNoArguments()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.Namespace = "MyNamespace";
            builder.ContainerName = "MyContainer";
            FunctionConfiguration function = builder.Function("Format");

            // Assert
            Assert.Equal("Format", function.Name);
            Assert.Equal(ProcedureKind.Function, function.Kind);
            Assert.NotNull(function.Parameters);
            Assert.Empty(function.Parameters);
            Assert.Null(function.ReturnType);
            Assert.False(function.IsSideEffecting);
            Assert.False(function.IsComposable);
            Assert.False(function.IsBindable);
            Assert.False(function.SupportedInFilter);
            Assert.False(function.SupportedInOrderBy);
            Assert.Equal("MyContainer.Format", function.ContainerQualifiedName);
            Assert.Equal("MyContainer.Format", function.FullName);
            Assert.Equal("MyNamespace.MyContainer.Format", function.FullyQualifiedName);
            Assert.NotNull(builder.Procedures);
            Assert.Equal(1, builder.Procedures.Count());
        }
 public override void Apply(EntityTypeConfiguration entity, ODataModelBuilder model)
 {
     if (entity.IsAbstract == null)
     {
         entity.IsAbstract = entity.ClrType.IsAbstract;
     }
 }
        public void CreateEntityTypeWithRelationship()
        {
            var builder = new ODataModelBuilder().Add_Customer_EntityType().Add_Order_EntityType().Add_OrderCustomer_Relationship();

            var model = builder.GetServiceModel();
            var orderType = model.SchemaElements.OfType<IEdmEntityType>().SingleOrDefault(t => t.Name == "Order");
            Assert.NotNull(orderType);
            Assert.Equal("Order", orderType.Name);
            Assert.Equal(typeof(Order).Namespace, orderType.Namespace);
            Assert.Equal("OrderId", orderType.DeclaredKey.Single().Name);
            Assert.Equal(5, orderType.DeclaredProperties.Count());
            Assert.Equal(1, orderType.NavigationProperties().Count());
            var deliveryDateProperty = orderType.DeclaredProperties.Single(dp => dp.Name == "DeliveryDate");
            Assert.NotNull(deliveryDateProperty);
            Assert.True(deliveryDateProperty.Type.IsNullable);

            Assert.Equal("Customer", orderType.NavigationProperties().First().Name);
            Assert.Equal("Customer", orderType.NavigationProperties().First().ToEntityType().Name);

            var customerType = model.SchemaElements.OfType<IEdmEntityType>().SingleOrDefault(t => t.Name == "Customer");
            Assert.NotNull(customerType);
            Assert.Equal("Customer", customerType.Name);
            Assert.Equal(typeof(Customer).Namespace, customerType.Namespace);
            Assert.Equal("CustomerId", customerType.DeclaredKey.Single().Name);
            Assert.Equal(5, customerType.DeclaredProperties.Count());
        }
        public void CanCreateActionWithNoArguments()
        {
            // Arrange
            // Act
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.Namespace = "MyNamespace";
            builder.ContainerName = "MyContainer";
            ActionConfiguration action = builder.Action("Format");
            ActionConfiguration actionII = builder.Action("FormatII");
            actionII.Namespace = "MyNamespaceII";

            // Assert
            Assert.Equal("Format", action.Name);
            Assert.Equal(ProcedureKind.Action, action.Kind);
            Assert.NotNull(action.Parameters);
            Assert.Empty(action.Parameters);
            Assert.Null(action.ReturnType);
            Assert.True(action.IsSideEffecting);
            Assert.False(action.IsComposable);
            Assert.False(action.IsBindable);
            Assert.Equal("MyNamespace", action.Namespace);
            Assert.Equal("MyNamespace.Format", action.FullyQualifiedName);
            Assert.Equal("MyNamespaceII", actionII.Namespace);
            Assert.Equal("MyNamespaceII.FormatII", actionII.FullyQualifiedName);
            Assert.NotNull(builder.Procedures);
            Assert.Equal(2, builder.Procedures.Count());
        }
        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;
        }
        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 void CanUseRelativeLinks()
        {
            var builder = new ODataModelBuilder()
                            .Add_Customer_EntityType()
                            .Add_Order_EntityType()
                            .Add_CustomerOrders_Relationship()
                            .Add_Customers_EntitySet()
                            .Add_Orders_EntitySet()
                            .Add_CustomerOrders_Binding();


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

            var model = builder.GetEdmModel();

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

            //Assert.Equal("Customers", customersSet.GetUrl());
            ///Assert.Equal("Customers(24)", customersSet.GetEditLink(entityContext).ToString());
            //Assert.Equal("Orders/ByCustomerId/24", customersSet.FindBinding("Orders").GetLink(entityContext));
        }
        public void NonbindingParameterConfigurationSupportsParameterTypeAs(Type type, bool isNullable)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<Customer>();
            builder.ComplexType<Address>();
            builder.EnumType<Color>();

            // Act
            Type underlyingType = TypeHelper.GetUnderlyingTypeOrSelf(type);
            IEdmTypeConfiguration edmTypeConfiguration = builder.GetTypeConfigurationOrNull(type);
            if (underlyingType.IsEnum)
            {
                edmTypeConfiguration = builder.GetTypeConfigurationOrNull(underlyingType);
                if (edmTypeConfiguration != null && isNullable)
                {
                    edmTypeConfiguration = ((EnumTypeConfiguration)edmTypeConfiguration).GetNullableEnumTypeConfiguration();
                }
            }
            NonbindingParameterConfiguration parameter = new NonbindingParameterConfiguration("name",
                edmTypeConfiguration);

            // Assert
            Assert.Equal(isNullable, parameter.OptionalParameter);
        }
        public void Apply(IEntitySetConfiguration configuration, ODataModelBuilder model)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            // We only need to configure the EditLink by convention, ReadLink and IdLink both delegate to EditLink
            if (configuration.GetEditLink() == null)
            {
                configuration.HasEditLink(entityContext => 
                    {
                        string routeName = SelfRouteName ?? ODataRouteNames.GetById;
                        string editlink = entityContext.UrlHelper.Link(
                            routeName,
                            new
                            {
                                controller = configuration.Name,
                                id = ConventionsHelpers.GetEntityKeyValue(entityContext, configuration.EntityType)
                            });
                        if (editlink == null)
                        {
                            throw Error.InvalidOperation(SRResources.GetByIdRouteMissingOrIncorrect, routeName);
                        }
                        return new Uri(editlink);
                    });
            }
        }
        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 EntitySetConfiguration(ODataModelBuilder modelBuilder, EntityTypeConfiguration entityType, string name)
        {
            if (modelBuilder == null)
            {
                throw Error.ArgumentNull("modelBuilder");
            }

            if (entityType == null)
            {
                throw Error.ArgumentNull("entityType");
            }

            if (name == null)
            {
                throw Error.ArgumentNull("name");
            }

            _modelBuilder = modelBuilder;
            Name = name;
            EntityType = entityType;
            ClrType = entityType.ClrType;
            _url = Name;

            _editLinkFactory = null;
            _readLinkFactory = null;
            _navigationPropertyLinkBuilders = new Dictionary<NavigationPropertyConfiguration, Func<EntityInstanceContext, IEdmNavigationProperty, Uri>>();
            _entitySetBindings = new Dictionary<NavigationPropertyConfiguration, NavigationPropertyBinding>();
        }
        public void Apply(EntitySetConfiguration configuration, ODataModelBuilder model)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }

            // generate links without cast for declared and inherited navigation properties
            foreach (EntityTypeConfiguration entity in configuration.EntityType.ThisAndBaseTypes())
            {
                foreach (NavigationPropertyConfiguration property in entity.NavigationProperties)
                {
                    if (configuration.GetNavigationPropertyLink(property) == null)
                    {
                        configuration.HasNavigationPropertyLink(
                                property,
                                (entityContext, navigationProperty) => GenerateNavigationPropertyLink(entityContext, navigationProperty, configuration, includeCast: false));
                    }
                }
            }

            // generate links with cast for navigation properties in derived types.
            foreach (EntityTypeConfiguration entity in model.DerivedTypes(configuration.EntityType))
            {
                foreach (NavigationPropertyConfiguration property in entity.NavigationProperties)
                {
                    if (configuration.GetNavigationPropertyLink(property) == null)
                    {
                        configuration.HasNavigationPropertyLink(
                                property,
                                (entityContext, navigationProperty) => GenerateNavigationPropertyLink(entityContext, navigationProperty, configuration, includeCast: true));
                    }
                }
            }
        }
        public void Apply_SingleForeignKeyOnForeignKeyProperty_Works()
        {
            // Arrange
            Type dependentType = typeof(SingleDependentEntity2);

            ODataModelBuilder builder = new ODataModelBuilder();
            builder.Entity<PrincipalEntity>().HasKey(p => p.PrincipalIntId);

            EntityTypeConfiguration dependentEntity = builder.AddEntity(dependentType);

            PropertyInfo expectPropertyInfo = dependentType.GetProperty("PrincipalId");
            PrimitivePropertyConfiguration primitiveProperty = dependentEntity.AddProperty(expectPropertyInfo);

            PropertyInfo propertyInfo = dependentType.GetProperty("Principal");
            NavigationPropertyConfiguration navigation = dependentEntity.AddNavigationProperty(propertyInfo,
                EdmMultiplicity.ZeroOrOne);
            navigation.AddedExplicitly = false;

            // Act
            new ForeignKeyAttributeConvention().Apply(primitiveProperty, dependentEntity);

            // Assert
            PropertyInfo actualPropertyInfo = Assert.Single(navigation.DependentProperties);
            Assert.Same(expectPropertyInfo, actualPropertyInfo);

            Assert.Equal("PrincipalIntId", Assert.Single(navigation.PrincipalProperties).Name);
            Assert.False(primitiveProperty.OptionalProperty);
        }
        public void Apply_MultiForeignKeysOnNavigationProperty_Works()
        {
            // Arrange
            Type dependentType = typeof(MultiDependentEntity);

            ODataModelBuilder builder = new ODataModelBuilder();
            builder.Entity<PrincipalEntity>().HasKey(p => new { p.PrincipalIntId, p.PrincipalStringId });

            EntityTypeConfiguration dependentEntity = builder.AddEntity(dependentType);

            PropertyInfo expectPropertyInfo1 = dependentType.GetProperty("PrincipalId1");
            dependentEntity.AddProperty(expectPropertyInfo1);

            PropertyInfo expectPropertyInfo2 = dependentType.GetProperty("PrincipalId2");
            dependentEntity.AddProperty(expectPropertyInfo2);

            PropertyInfo propertyInfo = typeof(MultiDependentEntity).GetProperty("Principal");
            NavigationPropertyConfiguration navigation = dependentEntity.AddNavigationProperty(propertyInfo,
                EdmMultiplicity.One);
            navigation.AddedExplicitly = false;

            // Act
            new ForeignKeyAttributeConvention().Apply(navigation, dependentEntity);

            // Assert
            Assert.Equal(2, navigation.DependentProperties.Count());
            Assert.Same(expectPropertyInfo1, navigation.DependentProperties.First());
            Assert.Same(expectPropertyInfo2, navigation.DependentProperties.Last());

            Assert.Equal(2, navigation.PrincipalProperties.Count());
            Assert.Equal("PrincipalIntId", navigation.PrincipalProperties.First().Name);
            Assert.Equal("PrincipalStringId", navigation.PrincipalProperties.Last().Name);
        }
        public void Apply_KeyNameConventions_Works()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            EntityTypeConfiguration principalEntity = builder.AddEntity(typeof(DiscoveryPrincipalEntity));
            PropertyInfo propertyInfo = typeof(DiscoveryPrincipalEntity).GetProperty("DiscoveryPrincipalEntityId");
            principalEntity.HasKey(propertyInfo);

            EntityTypeConfiguration dependentEntity = builder.AddEntity(typeof(DiscoveryDependentEntity));
            PropertyInfo expectPropertyInfo = typeof(DiscoveryDependentEntity).GetProperty("DiscoveryPrincipalEntityId");
            dependentEntity.AddProperty(expectPropertyInfo);

            PropertyInfo navigationPropertyInfo = typeof(DiscoveryDependentEntity).GetProperty("Principal");
            NavigationPropertyConfiguration navigation = dependentEntity.AddNavigationProperty(navigationPropertyInfo,
                EdmMultiplicity.One);
            navigation.AddedExplicitly = false;

            // Act
            new ForeignKeyDiscoveryConvention().Apply(navigation, dependentEntity);

            // Assert
            PropertyInfo actualPropertyInfo = Assert.Single(navigation.DependentProperties);
            Assert.Same(expectPropertyInfo, actualPropertyInfo);

            PropertyInfo principalProperty = Assert.Single(navigation.PrincipalProperties);
            Assert.Equal("DiscoveryPrincipalEntityId", principalProperty.Name);
        }
Beispiel #31
0
 // Singleton -> Singleton
 public static ODataModelBuilder Add_MicrosoftCEO_Binding(this ODataModelBuilder builder)
 {
     builder.Singleton <Company>("OsCorp").HasSingletonBinding(c => c.CEO, "CEO");
     return(builder);
 }
Beispiel #32
0
 // Adds a Customer EntitySet with no key properties
 public static ODataModelBuilder Add_Customers_No_Keys_EntitySet(this ODataModelBuilder builder)
 {
     builder.Add_Customer_No_Keys_EntityType().EntitySet <Customer>("Customers");
     return(builder);
 }
Beispiel #33
0
 public static ODataModelBuilder Add_Orders_EntitySet(this ODataModelBuilder builder)
 {
     builder.EntitySet <Order>("Orders");
     return(builder);
 }
Beispiel #34
0
 // Adds a Customer EntitySet but allows caller to configure keys
 public static ODataModelBuilder Add_Customers_With_Keys_EntitySet <TKey>(this ODataModelBuilder builder, Expression <Func <Customer, TKey> > keyDefinitionExpression)
 {
     builder.Add_Customer_With_Keys_EntityType(keyDefinitionExpression).EntitySet <Customer>("Customers");
     return(builder);
 }
Beispiel #35
0
 public static ODataModelBuilder Add_Customers_Singleton(this ODataModelBuilder builder)
 {
     builder.Add_Customer_EntityType().Singleton <Customer>("VipCustomer");
     return(builder);
 }
Beispiel #36
0
 public static ODataModelBuilder Add_OrderCustomer_Relationship(this ODataModelBuilder builder)
 {
     builder.EntityType <Order>().HasRequired(o => o.Customer);
     return(builder);
 }
Beispiel #37
0
 public static ODataModelBuilder Add_CustomerCompany_Relationship(this ODataModelBuilder builder)
 {
     builder.EntityType <Customer>().HasOptional(c => c.Company);
     return(builder);
 }
Beispiel #38
0
 public static ODataModelBuilder Add_CustomerOrders_Relationship(this ODataModelBuilder builder)
 {
     builder.EntityType <Customer>().HasMany(c => c.Orders);
     return(builder);
 }
Beispiel #39
0
 // EntitySet -> Singleton
 public static ODataModelBuilder Add_CompaniesCEO_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Company>("Companies").HasSingletonBinding(c => c.CEO, "CEO");
     return(builder);
 }
Beispiel #40
0
 // Singleton -> EntitySet
 public static ODataModelBuilder Add_MicrosoftEmployees_Binding(this ODataModelBuilder builder)
 {
     builder.Singleton <Company>("OsCorp").HasManyBinding(c => c.ComplanyEmployees, "Employees");
     return(builder);
 }
Beispiel #41
0
 public static ODataModelBuilder Add_EmployeeComplany_Relationship(this ODataModelBuilder builder)
 {
     builder.EntityType <Employee>().HasRequired(o => o.WorkCompany);
     return(builder);
 }
Beispiel #42
0
 // EntitySet -> EntitySet
 public static ODataModelBuilder Add_CompaniesEmployees_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Company>("Companies").HasManyBinding(c => c.ComplanyEmployees, "Employees");
     return(builder);
 }
Beispiel #43
0
 public static ODataModelBuilder Add_Company_Singleton(this ODataModelBuilder builder)
 {
     builder.Add_Company_EntityType().Singleton <Company>("OsCorp");
     return(builder);
 }
Beispiel #44
0
 public static ODataModelBuilder Add_CompanyEmployees_Relationship(this ODataModelBuilder builder)
 {
     builder.EntityType <Company>().HasMany(c => c.ComplanyEmployees);
     builder.EntityType <Company>().HasRequired(c => c.CEO, (company, employee) => company.CEOID == employee.EmployeeID, employee => employee.IsCeoOf);
     return(builder);
 }
Beispiel #45
0
        public static ODataModelBuilder Add_Customer_EntityType_With_DuplicatedAddress(this ODataModelBuilder builder)
        {
            builder.Add_Customer_EntityType();
            builder.Add_Address_ComplexType();
            var customer = builder.EntityType <Customer>();

            customer.ComplexProperty(c => c.Address);
            customer.ComplexProperty(c => c.WorkAddress);
            customer.Property(c => c.City);
            return(builder);
        }
Beispiel #46
0
 public static ODataModelBuilder Add_Customer_EntityType_With_CollectionProperties(this ODataModelBuilder builder)
 {
     builder.Add_Customer_EntityType();
     builder.EntityType <Customer>().CollectionProperty(c => c.Aliases);
     builder.EntityType <Customer>().CollectionProperty(c => c.Addresses);
     return(builder);
 }
Beispiel #47
0
        public static ODataModelBuilder Add_Customer_EntityType_With_DynamicProperties(this ODataModelBuilder builder)
        {
            builder.Add_Customer_EntityType();
            var customer = builder.EntityType <Customer>();

            customer.HasDynamicProperties(c => c.DynamicProperties);
            return(builder);
        }
Beispiel #48
0
 public static IEdmModel GetServiceModel(this ODataModelBuilder builder)
 {
     return(EdmModelHelperMethods.BuildEdmModel(builder));
 }
Beispiel #49
0
 public void CanEmitModelWithTwoEntitiesAndARelationship()
 {
     var builder = new ODataModelBuilder().Add_Order_EntityType().Add_Customer_EntityType().Add_CustomerOrders_Relationship();
     var model   = builder.GetServiceModel();
     var csdl    = GetCSDL(model);
 }
        public void CanCreateEdmModel_ForBindableFunction_WithSupportedParameterType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            EntityTypeConfiguration <Customer> customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.Property(c => c.Name);

            // Act
            FunctionConfiguration functionBuilder = customer.Function("FunctionName");

            functionBuilder.Parameter <int>("primitive");
            functionBuilder.CollectionParameter <int>("collectionPrimitive");

            functionBuilder.Parameter <bool?>("nullablePrimitive");
            functionBuilder.CollectionParameter <bool?>("nullableCollectionPrimitive");

            functionBuilder.Parameter <Color>("enum");
            functionBuilder.CollectionParameter <Color>("collectionEnum");

            functionBuilder.Parameter <Color?>("nullableEnum");
            functionBuilder.CollectionParameter <Color?>("nullableCollectionEnum");

            functionBuilder.Parameter <Address>("complex");
            functionBuilder.CollectionParameter <Address>("collectionComplex");

            functionBuilder.EntityParameter <Customer>("entity");
            functionBuilder.CollectionEntityParameter <Customer>("collectionEntity");

            functionBuilder.Returns <bool>();

            IEdmModel model = builder.GetEdmModel();

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

            Assert.False(function.IsComposable);
            Assert.True(function.IsBound);
            Assert.Equal("FunctionName", function.Name);
            Assert.NotNull(function.ReturnType);

            Assert.Equal(13, function.Parameters.Count());

            function.AssertHasParameter(model, BindingParameterConfiguration.DefaultBindingParameterName, typeof(Customer), true);

            function.AssertHasParameter(model, parameterName: "primitive", parameterType: typeof(int), isNullable: false);
            function.AssertHasParameter(model, parameterName: "collectionPrimitive", parameterType: typeof(IList <int>), isNullable: false);

            function.AssertHasParameter(model, parameterName: "nullablePrimitive", parameterType: typeof(bool?), isNullable: true);
            function.AssertHasParameter(model, parameterName: "nullableCollectionPrimitive", parameterType: typeof(IList <bool?>), isNullable: true);

            function.AssertHasParameter(model, parameterName: "enum", parameterType: typeof(Color), isNullable: false);
            function.AssertHasParameter(model, parameterName: "collectionEnum", parameterType: typeof(IList <Color>), isNullable: false);

            function.AssertHasParameter(model, parameterName: "nullableEnum", parameterType: typeof(Color?), isNullable: true);
            function.AssertHasParameter(model, parameterName: "nullableCollectionEnum", parameterType: typeof(IList <Color?>), isNullable: true);

            function.AssertHasParameter(model, parameterName: "complex", parameterType: typeof(Address), isNullable: true);
            function.AssertHasParameter(model, parameterName: "collectionComplex", parameterType: typeof(IList <Address>), isNullable: true);

            function.AssertHasParameter(model, parameterName: "entity", parameterType: typeof(Customer), isNullable: true);
            function.AssertHasParameter(model, parameterName: "collectionEntity", parameterType: typeof(IList <Customer>), isNullable: true);
        }
Beispiel #51
0
 public void CanEmitModelWithSingleEntity()
 {
     var builder = new ODataModelBuilder().Add_Customer_EntityType();
     var model   = builder.GetServiceModel();
     var csdl    = GetCSDL(model);
 }
Beispiel #52
0
 public void CanEmitModelWithSingleComplexType()
 {
     var builder = new ODataModelBuilder().Add_Address_ComplexType();
     var model   = builder.GetServiceModel();
     var csdl    = GetCSDL(model);
 }
 public NavigationSourceLinkBuilderAnnotationTest()
 {
     _modelBuilder = ODataModelBuilderMocks.GetModelBuilderMock <ODataModelBuilder>();
     _entitySet    = _modelBuilder.AddEntitySet("Customers", _modelBuilder.AddEntityType(typeof(Customer)));
 }
        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");

            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 suppliers = modelBuilder.EntitySet <Supplier>("Suppliers");

            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);

            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.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);

            return(modelBuilder.GetEdmModel());
        }
Beispiel #55
0
        public void Apply(ODataModelBuilder builder, ApiVersion apiVersion)
        {
            var category = builder.EntitySet <Categories>(nameof(Categories)).EntityType;

            category.HasKey(p => p.CategoryId);
        }
        public void MaxDataServiceVersion_RoundTrips()
        {
            ODataModelBuilder builder = new ODataModelBuilder();

            ReflectionAssert.Property(builder, b => b.MaxDataServiceVersion, new Version(4, 0), allowNull: false, roundTripTestValue: new Version(1, 0));
        }
Beispiel #57
0
 public static ODataModelBuilder Add_CustomerOrders_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Customer>("Customers").HasManyBinding(c => c.Orders, "Orders");
     return(builder);
 }
Beispiel #58
0
 private void ConfigureV2(ODataModelBuilder builder) => ConfigureCurrent(builder).Ignore(p => p.Phone);
Beispiel #59
0
 public static ODataModelBuilder Add_OrderCustomer_Binding(this ODataModelBuilder builder)
 {
     builder.EntitySet <Order>("Orders").HasRequiredBinding(o => o.Customer, "Customer");
     return(builder);
 }
Beispiel #60
0
        public static EntitySetConfiguration CreateOrReuseEntitySet <TElementEntityType>(ODataModelBuilder builder, string entitySetName) where TElementEntityType : class
        {
            EntitySetConfiguration entitySet = builder.EntitySets.SingleOrDefault(s => s.Name == entitySetName);

            if (entitySet == null)
            {
                builder.EntitySet <TElementEntityType>(entitySetName);
                entitySet = builder.EntitySets.Single(s => s.Name == entitySetName);
            }
            else
            {
                builder.EntityType <TElementEntityType>();
            }
            return(entitySet);
        }