Esempio n. 1
0
        public static IEdmModel NewNonConventionalBuildModel()
        {
            var builder = new ODataModelBuilder();
            var color   = builder.EnumType <Color>();

            color.Member(Color.Red);
            color.Member(Color.Blue);
            color.Member(Color.Green);
            var address = builder.ComplexType <Address>();

            address.Property(a => a.Country);
            address.Property(a => a.City);
            address.HasDynamicProperties(a => a.Dynamics);
            var subAddress = builder.ComplexType <SubAddress>().DerivesFrom <Address>();

            subAddress.Property(s => s.Street);
            var customer = builder.EntityType <Customer>();

            customer.HasKey(c => c.CustomerId);
            customer.ComplexProperty(c => c.Location);
            customer.HasMany(c => c.Orders);
            var order = builder.EntityType <Order>();

            order.HasKey(o => o.OrderId);
            order.Property(o => o.Token);
            builder.EntityType <Registration>().HasKey(r => new { r.ParticipantId, r.ThreadId });
            builder.EntityType <Participant>().HasKey(p => p.Login);
            builder.EntityType <Thread>().HasKey(t => t.Id);
            builder.EntityType <Box>().HasKey(b => b.Id);
            builder.EntitySet <Thread>("Threads");
            builder.EntitySet <Box>("Boxes");
            builder.EntitySet <Participant>("Participants");
            return(builder.GetEdmModel());
        }
Esempio n. 2
0
        public void CanCreateDerivedComplexType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.ComplexType <BaseComplexType>().Abstract().Property(v => v.BaseProperty);
            builder.ComplexType <DerivedComplexType>().DerivesFrom <BaseComplexType>().Property(v => v.DerivedProperty);

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

            // Assert
            IEdmComplexType baseComplexType = model.AssertHasComplexType(typeof(BaseComplexType));

            Assert.Null(baseComplexType.BaseComplexType());
            Assert.Single(baseComplexType.Properties());
            baseComplexType.AssertHasPrimitiveProperty(model, "BaseProperty", EdmPrimitiveTypeKind.String, true);

            IEdmComplexType derivedComplexType = model.AssertHasComplexType(typeof(DerivedComplexType));

            Assert.Equal(baseComplexType, derivedComplexType.BaseComplexType());
            Assert.Equal(2, derivedComplexType.Properties().Count());
            derivedComplexType.AssertHasPrimitiveProperty(model, "BaseProperty", EdmPrimitiveTypeKind.String, true);
            derivedComplexType.AssertHasPrimitiveProperty(model, "DerivedProperty", EdmPrimitiveTypeKind.Int32, false);
        }
Esempio n. 3
0
        public void AddProperty_Throws_WhenRedefineBaseTypeProperty_OnDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<BaseComplexType>().Property(v => v.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType<DerivedComplexType>().DerivesFrom<BaseComplexType>().Property(v => v.BaseProperty),
                "propertyInfo",
                "Cannot redefine property 'BaseProperty' already defined on the base type 'Microsoft.Test.AspNet.OData.Builder.BaseComplexType'.");
        }
Esempio n. 4
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();
        }
Esempio n. 5
0
        public void AddProperty_Throws_WhenDefinePropertyOnBaseTypeAlreadyPresentInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<DerivedComplexType>().DerivesFrom<BaseComplexType>().Property(m => m.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType<BaseComplexType>().Property(v => v.BaseProperty),
                "propertyInfo",
                "Cannot define property 'BaseProperty' in the base type 'Microsoft.Test.AspNet.OData.Builder.BaseComplexType' " +
                "as the derived type 'Microsoft.Test.AspNet.OData.Builder.DerivedComplexType' already defines it.");
        }
Esempio n. 6
0
        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).IsNullable();
            windowType.CollectionProperty(w => w.OptionalShapes);
            windowType.CollectionProperty(w => w.PolygonalShapes);
            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);
            windows.HasOptionalBinding(c => c.Parent, "Windows");

            builder.Namespace = typeof(Window).Namespace;

            return(builder.GetEdmModel());
        }
Esempio n. 7
0
        public void DerivesFrom_Throws_WhenSettingTheBaseType_IfDuplicatePropertyInDerivedType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.ComplexType <BaseComplexType>().Property(v => v.BaseProperty);
            builder.ComplexType <SubDerivedComplexType>().DerivesFrom <DerivedComplexType>().Property(c => c.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType <DerivedComplexType>().DerivesFrom <BaseComplexType>(),
                "propertyInfo",
                "Cannot define property 'BaseProperty' in the base type 'Microsoft.AspNet.OData.Test.Builder.DerivedComplexType' as " +
                "the derived type 'Microsoft.AspNet.OData.Test.Builder.SubDerivedComplexType' already defines it.");
        }
Esempio n. 8
0
        public void DerivesFrom_Throws_WhenSettingTheBaseType_IfDuplicatePropertyInBaseType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.ComplexType<BaseComplexType>().Property(v => v.BaseProperty);
            ComplexTypeConfiguration<DerivedComplexType> derivedComplex = builder.ComplexType<DerivedComplexType>();
            derivedComplex.Property(m => m.BaseProperty);

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => derivedComplex.DerivesFrom<BaseComplexType>(),
                "propertyInfo",
                "Cannot redefine property 'BaseProperty' already defined on the base type 'Microsoft.Test.AspNet.OData.Builder.BaseComplexType'.");
        }
Esempio n. 9
0
        public void CreateComplexTypeWith_OneToOneOrZero_NavigationProperty()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Customer>().HasKey(c => c.CustomerId);

            ComplexTypeConfiguration <Order> order = builder.ComplexType <Order>();

            order.HasOptional(o => o.Customer);

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

            // Assert
            IEdmEntityType customerType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>());

            Assert.Equal("Microsoft.OData.ModelBuilder.Tests.TestModels.Customer", customerType.FullName());
            Assert.Equal("CustomerId", customerType.DeclaredKey.Single().Name);
            Assert.Single(customerType.DeclaredProperties);
            Assert.Empty(customerType.NavigationProperties());

            IEdmComplexType orderType = Assert.Single(model.SchemaElements.OfType <IEdmComplexType>());

            Assert.Equal("Microsoft.OData.ModelBuilder.Tests.TestModels.Order", orderType.FullName());

            IEdmNavigationProperty navProperty = Assert.Single(orderType.NavigationProperties());

            Assert.Equal(EdmMultiplicity.ZeroOrOne, navProperty.TargetMultiplicity());
            Assert.Equal("Customer", navProperty.Name);
            Assert.True(navProperty.Type.IsEntity());
            Assert.Same(customerType, navProperty.Type.Definition);
        }
Esempio n. 10
0
        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.Nullable);
        }
Esempio n. 11
0
        public static IEdmModel GetExplicitModel(string singletonName)
        {
            ODataModelBuilder builder = new ODataModelBuilder();

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

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

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

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

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

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

            builder.Namespace = typeof(Partner).Namespace;

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

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

            return builder.GetEdmModel();
        }
Esempio n. 12
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(ODataRouteNames.Default, new { })));
                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);
        }
Esempio n. 13
0
        public void CreateComplexTypeWith_OneToMany_NavigationProperty()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            builder.EntityType <Order>().HasKey(o => o.OrderId);

            ComplexTypeConfiguration <Customer> customer = builder.ComplexType <Customer>();

            customer.HasMany(c => c.Orders);

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

            // Assert
            IEdmEntityType orderType = Assert.Single(model.SchemaElements.OfType <IEdmEntityType>());

            Assert.Equal("Microsoft.AspNet.OData.Test.Builder.TestModels.Order", orderType.FullName());
            Assert.Equal("OrderId", orderType.DeclaredKey.Single().Name);
            Assert.Single(orderType.DeclaredProperties);
            Assert.Empty(orderType.NavigationProperties());

            IEdmComplexType customerType = Assert.Single(model.SchemaElements.OfType <IEdmComplexType>());

            Assert.Equal("Microsoft.AspNet.OData.Test.Builder.TestModels.Customer", customerType.FullName());

            IEdmNavigationProperty navProperty = Assert.Single(customerType.NavigationProperties());

            Assert.Equal(EdmMultiplicity.Many, navProperty.TargetMultiplicity());
            Assert.Equal("Orders", navProperty.Name);
            Assert.True(navProperty.Type.IsCollection());
            Assert.Same(orderType, navProperty.Type.AsCollection().ElementType().Definition);
        }
        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);
        }
Esempio n. 15
0
        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).IsUnsortable();
            limitedEntities.EntityType.HasOptional(l => l.RelatedEntity);
            limitedEntities.EntityType.CollectionProperty(cp => cp.Integers);

            // Configure LimitedRelatedEntity
            EntitySetConfiguration <LimitedRelatedEntity> limitedRelatedEntities =
                builder.EntitySet <LimitedRelatedEntity>("LimitedRelatedEntities");

            limitedRelatedEntities.EntityType.HasKey(p => p.Id);
            limitedRelatedEntities.EntityType.HasOptional(p => p.BackReference).IsUnsortable();
            limitedRelatedEntities.EntityType.ComplexProperty(p => p.RelatedComplexProperty).IsUnsortable();

            // Configure SpecializedEntity
            EntityTypeConfiguration <LimitedSpecializedEntity> specializedEntity =
                builder.EntityType <LimitedSpecializedEntity>().DerivesFrom <LimitedRelatedEntity>();

            specializedEntity.Namespace = "NS";
            specializedEntity.ComplexProperty(p => p.SpecializedComplexProperty).IsUnsortable();

            // Configure Complextype
            ComplexTypeConfiguration <LimitedComplexType> complexType = builder.ComplexType <LimitedComplexType>();

            complexType.Property(p => p.UnsortableValue).IsUnsortable();
            complexType.Property(p => p.Value);

            return(builder.GetEdmModel());
        }
Esempio n. 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.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.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);
        }
        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();
        }
Esempio n. 18
0
        private static IEdmModel GetEdmModel()
        {
            ODataModelBuilder builder = ODataConventionModelBuilderFactory.Create();

            builder.EntitySet <OpenCustomer>("OpenCustomers");
            builder.ComplexType <Building>();
            return(builder.GetEdmModel());
        }
Esempio n. 19
0
        public static ODataModelBuilder Add_RecursiveZipCode_ComplexType(this ODataModelBuilder builder)
        {
            var zipCode = builder.ComplexType <RecursiveZipCode>();

            zipCode.Property(z => z.Part1);
            zipCode.Property(z => z.Part2).IsNullable();
            return(builder);
        }
Esempio n. 20
0
        public static ODataModelBuilder Add_ZipCode_ComplexType(this ODataModelBuilder builder)
        {
            var zipCode = builder.ComplexType <ZipCode>();

            zipCode.Property(z => z.Part1);
            zipCode.Property(z => z.Part2).IsOptional();
            return(builder);
        }
Esempio n. 21
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 static ComplexTypeConfiguration <TEntityType> ComplexType <TEntityType>(
            this ODataModelBuilder builder, Action <ComplexTypeConfiguration <TEntityType> > action)
            where TEntityType : class
        {
            var cfg = builder.ComplexType <TEntityType>();

            action(cfg);
            return(cfg);
        }
Esempio n. 23
0
        public static ODataModelBuilder Add_Address_ComplexType(this ODataModelBuilder builder)
        {
            var address = builder.ComplexType <Address>();

            address.Property(a => a.HouseNumber);
            address.Property(a => a.Street);
            address.Property(a => a.City);
            address.Property(a => a.State);
            return(builder);
        }
Esempio n. 24
0
        public static IEdmModel GetEdmModel()
        {
            //ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            var builder = new ODataModelBuilder {
                Namespace = typeof(Person).Namespace, ContainerName = "DefaultContainer"
            };

            ComplexTypeConfiguration <Range> rangeType = builder.ComplexType <Range>();

            //rangeType.Select();
            rangeType.Property(c => c.minValue);
            rangeType.Property(c => c.maxValue);

            var personConfig = builder.AddEntityType(typeof(Person));

            personConfig.HasKey(typeof(Person).GetProperty("ID"));
            personConfig.AddProperty(typeof(Person).GetProperty("Name"));
            personConfig.AddNavigationProperty(typeof(Person).GetProperty("Car"), EdmMultiplicity.ZeroOrOne);
            //personConfig.AddComplexProperty(typeof(Person).GetProperty("minValue"));
            //personConfig.AddComplexProperty(typeof(Person).GetProperty("maxValue"));
            personConfig.AddComplexProperty(typeof(Person).GetProperty("Ranges"));

            var carConfig = builder.AddEntityType(typeof(Car));

            carConfig.HasKey(typeof(Car).GetProperty("ID"));
            carConfig.AddProperty(typeof(Car).GetProperty("AmountMade"));
            carConfig.AddProperty(typeof(Car).GetProperty("APK"));
            carConfig.AddProperty(typeof(Car).GetProperty("Name"));
            carConfig.AddProperty(typeof(Car).GetProperty("TimeWhenAddedToDatabase"));
            carConfig.AddEnumProperty(typeof(Car).GetProperty("Brand"));
            carConfig.AddNavigationProperty(typeof(Car).GetProperty("People"), EdmMultiplicity.Many);

            var _Brands = builder.AddEnumType(typeof(_Brands));

            _Brands.AddMember(Models._Brands.Audi);
            _Brands.AddMember(Models._Brands.BMW);
            _Brands.AddMember(Models._Brands.Ferrari);
            _Brands.AddMember(Models._Brands.Ford);
            _Brands.AddMember(Models._Brands.Honda);
            _Brands.AddMember(Models._Brands.Mercedes);
            _Brands.AddMember(Models._Brands.Mini);
            _Brands.AddMember(Models._Brands.Nissan);
            _Brands.AddMember(Models._Brands.Porsche);
            _Brands.AddMember(Models._Brands.Tesla);
            _Brands.AddMember(Models._Brands.Toyota);
            _Brands.AddMember(Models._Brands.Volkswagen);

            builder.AddEntitySet("people", personConfig);
            builder.AddEntitySet("cars", carConfig);

            var edmModel = builder.GetEdmModel();

            //return builder.GetEdmModel();
            return(edmModel);
        }
        public void CreateInfiniteRecursiveComplexTypeDefinitionFails()
        {
            var builder = new ODataModelBuilder()
                .Add_ZipCode_ComplexType();

            var zipCode = builder.ComplexType<ZipCode>();

            Assert.Throws<InvalidOperationException>(
                () => zipCode.ComplexProperty(z => z.Recursive),
                "The complex type 'System.Web.Http.OData.Builder.TestModels.ZipCode' has a reference to itself through the property 'Recursive'. A recursive loop of complex types is not allowed.");
        }
        public ComplexTypeTest()
        {
            ODataModelBuilder model = new ODataModelBuilder();
            var person = model.ComplexType<Person>();
            person.Property(p => p.Age);
            person.Property(p => p.FirstName);
            person.ComplexProperty(p => p.FavoriteHobby);
            person.ComplexProperty(p => p.Gender);

            _formatter = new ODataMediaTypeFormatter(model.GetEdmModel()) { IsClient = true };
        }
Esempio n. 27
0
        public void DerivesFrom_Throws_IfDerivedTypeDoesnotDeriveFromBaseType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act & Assert
            ExceptionAssert.ThrowsArgument(
                () => builder.ComplexType <string>().DerivesFrom <BaseComplexType>(),
                "baseType",
                "'System.String' does not inherit from 'Microsoft.AspNet.OData.Test.Builder.BaseComplexType'.");
        }
        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 void CreateInfiniteRecursiveComplexTypeDefinitionFails()
        {
            var builder = new ODataModelBuilder()
                .Add_ZipCode_ComplexType();

            var zipCode = builder.ComplexType<ZipCode>();

            Assert.ThrowsArgument(
                () => zipCode.ComplexProperty(z => z.Recursive),
                "propertyInfo",
                "A recursive loop of complex types is not allowed.");
        }
Esempio n. 30
0
        public void CreateInfiniteRecursiveComplexTypeDefinitionFails()
        {
            var builder = new ODataModelBuilder()
                .Add_RecursiveZipCode_ComplexType();

            var zipCode = builder.ComplexType<RecursiveZipCode>();

            ExceptionAssert.ThrowsArgument(
                () => zipCode.ComplexProperty(z => z.Recursive),
                "propertyInfo",
                "The complex type 'Microsoft.Test.AspNet.OData.Builder.TestModels.RecursiveZipCode' has a reference to itself through the property 'Recursive'. A recursive loop of complex types is not allowed.");
        }
Esempio n. 31
0
        public ComplexTypeTest()
        {
            ODataModelBuilder model = new ODataModelBuilder();
            var person = model.ComplexType <Person>();

            person.Property(p => p.Age);
            person.Property(p => p.FirstName);
            person.ComplexProperty(p => p.FavoriteHobby);
            person.ComplexProperty(p => p.Gender);

            _formatter = new ODataMediaTypeFormatter(model.GetEdmModel());
        }
Esempio n. 32
0
        public void CanDeriveFromNull()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ComplexTypeConfiguration <DerivedComplexType> derivedComplex = builder.ComplexType <DerivedComplexType>();

            // Act
            derivedComplex.DerivesFromNothing();

            // Assert
            Assert.Null(derivedComplex.BaseType);
        }
Esempio n. 33
0
        public void DynamicDictionaryProperty_Works_ToSetOpenComplexType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            // Act
            ComplexTypeConfiguration<SimpleOpenComplexType> complexType = builder.ComplexType<SimpleOpenComplexType>();
            complexType.Property(c => c.IntProperty);
            complexType.HasDynamicProperties(c => c.DynamicProperties);

            // Act & Assert
            Assert.True(complexType.IsOpen);
        }
        /// <inheritdoc />
        public void Apply(ODataModelBuilder builder, ApiVersion apiVersion, string routePrefix)
        {
            builder.ComplexType <AdditionalServiceUpdateDto>();
            EntityTypeConfiguration <AdditionalServiceViewDto> additionalService = builder
                                                                                   .EntitySet <AdditionalServiceViewDto>(nameof(AdditionalService))
                                                                                   .EntityType;

            additionalService.HasKey(p => p.Id);
            additionalService
            .Filter()
            .OrderBy()
            .Page(50, 50)
            .Select();

            builder.ComplexType <ServiceUpdateDto>();
            EntityTypeConfiguration <ServiceViewDto> service = builder
                                                               .EntitySet <ServiceViewDto>(nameof(Service))
                                                               .EntityType;

            service.HasKey(p => p.Id);
            service
            .Expand()
            .Filter()
            .OrderBy()
            .Page(50, 50)
            .Select();

            EntityTypeConfiguration <ServiceTagAdditionalServiceDto> serviceTag = builder
                                                                                  .EntitySet <ServiceTagAdditionalServiceDto>(nameof(ServiceTagAdditionalService))
                                                                                  .EntityType;

            serviceTag.HasKey(p => new { p.ServiceId, p.AdditionalServiceId });
            serviceTag
            .Expand()
            .Filter()
            .OrderBy()
            .Page(50, 50)
            .Select();
        }
Esempio n. 35
0
        public void DerivesFrom_SetsBaseType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            ComplexTypeConfiguration <DerivedComplexType> derivedComplex = builder.ComplexType <DerivedComplexType>();

            // Act
            derivedComplex.DerivesFrom <BaseComplexType>();

            // Assert
            Assert.NotNull(derivedComplex.BaseType);
            Assert.Equal(typeof(BaseComplexType), derivedComplex.BaseType.ClrType);
        }
Esempio n. 36
0
        public void CanCreateAbstractComplexType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<BaseComplexType>().Abstract();

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

            // Assert
            IEdmComplexType baseComplexType = Assert.Single(model.SchemaElements.OfType<IEdmComplexType>());
            Assert.True(baseComplexType.IsAbstract);
        }
Esempio n. 37
0
        public void CanCreateDerivedComplexTypeInReverseOrder()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<DerivedComplexType>().DerivesFrom<BaseComplexType>();

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

            // Assert
            model.AssertHasComplexType(typeof(BaseComplexType));
            model.AssertHasComplexType(typeof(DerivedComplexType), typeof(BaseComplexType));
        }
        public void BindingParameterConfigurationThrowsWhenParameterTypeIsNotEntity()
        { 
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<Address>();

            // Act & Assert
            ArgumentException exception = Assert.Throws<ArgumentException>(() =>
            {
                BindingParameterConfiguration configuration = new BindingParameterConfiguration("name", builder.GetTypeConfigurationOrNull(typeof(Address)));
            });
            Assert.True(exception.Message.Contains(string.Format("'{0}'", typeof(Address).FullName)));
            Assert.Equal("parameterType", exception.ParamName);
        }
Esempio n. 39
0
        public static IEdmModel GetExplicitModel(WebRouteConfiguration configuration)
        {
            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);
            employee.HasInstanceAnnotations(c => c.InstanceAnnotations);

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

            employees.HasEditLink(link, true);
            employees.HasIdLink(link, true);
            builder.Namespace = "NS";
            return(builder.GetEdmModel());
        }
        public void CreateComplexTypePropertyInComplexType()
        {
            var builder = new ODataModelBuilder()
                .Add_Address_ComplexType();

            var address = builder.ComplexType<Address>();
            address.ComplexProperty(a => a.ZipCode);

            var model = builder.GetServiceModel();
            var addressType = model.SchemaElements.OfType<IEdmComplexType>().SingleOrDefault(se => se.Name == "Address");
            var zipCodeType = model.SchemaElements.OfType<IEdmComplexType>().SingleOrDefault(se => se.Name == "ZipCode");
            Assert.NotNull(addressType);
            Assert.NotNull(zipCodeType);
            var zipCodeProperty = addressType.FindProperty("ZipCode");
            Assert.NotNull(zipCodeProperty);
            Assert.Equal(zipCodeType.FullName(), zipCodeProperty.Type.AsComplex().ComplexDefinition().FullName());
        }
Esempio n. 41
0
        public void CreateNullableEnumType()
        {
            // Arrange
            var builder = new ODataModelBuilder().Add_Color_EnumType();
            var complexTypeConfiguration = builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            complexTypeConfiguration.EnumProperty(c => c.NullableColor);

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

            // Assert
            Assert.Equal(1, complexType.Properties().Count());
            var nullableColor = complexType.Properties().SingleOrDefault(p => p.Name == "NullableColor");
            Assert.NotNull(nullableColor);
            Assert.True(nullableColor.Type.IsEnum());
            Assert.True(nullableColor.Type.IsNullable);
        }
Esempio n. 42
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();
        }
        public void NonbindingParameterConfigurationSupportsParameterCollectionTypeAs(Type type, bool isNullable)
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.EntityType<Customer>();
            builder.ComplexType<Address>();
            builder.EnumType<Color>();

            Type elementType;
            Assert.True(type.IsCollection(out elementType));

            // Act
            Type underlyingType = TypeHelper.GetUnderlyingTypeOrSelf(elementType);
            IEdmTypeConfiguration elementTypeConfiguration = builder.GetTypeConfigurationOrNull(underlyingType);
            CollectionTypeConfiguration collectionType = new CollectionTypeConfiguration(elementTypeConfiguration,
                typeof(IEnumerable<>).MakeGenericType(elementType));

            NonbindingParameterConfiguration parameter = new NonbindingParameterConfiguration("name", collectionType);

            // Assert
            Assert.Equal(isNullable, parameter.OptionalParameter);
        }
Esempio n. 44
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();
        }
        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).IsUnsortable();
            limitedEntities.EntityType.HasOptional(l => l.RelatedEntity);
            limitedEntities.EntityType.CollectionProperty(cp => cp.Integers);
            
            // Configure LimitedRelatedEntity
            EntitySetConfiguration<LimitedRelatedEntity> limitedRelatedEntities =
                builder.EntitySet<LimitedRelatedEntity>("LimitedRelatedEntities");
            limitedRelatedEntities.EntityType.HasKey(p => p.Id);
            limitedRelatedEntities.EntityType.HasOptional(p => p.BackReference).IsUnsortable();
            limitedRelatedEntities.EntityType.ComplexProperty(p => p.RelatedComplexProperty).IsUnsortable();

            // Configure SpecializedEntity
            EntityTypeConfiguration<LimitedSpecializedEntity> specializedEntity =
                builder.EntityType<LimitedSpecializedEntity>().DerivesFrom<LimitedRelatedEntity>();
            specializedEntity.Namespace = "NS";
            specializedEntity.ComplexProperty(p => p.SpecializedComplexProperty).IsUnsortable();

            // Configure Complextype
            ComplexTypeConfiguration<LimitedComplexType> complexType = builder.ComplexType<LimitedComplexType>();
            complexType.Property(p => p.UnsortableValue).IsUnsortable();
            complexType.Property(p => p.Value);

            return builder.GetEdmModel();
        }
        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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                                new KeyValuePathSegment(id.ToString()))
                        }));
                }, 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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                                new KeyValuePathSegment(id.ToString()))
                        }));
                }, 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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                                new KeyValuePathSegment(id.ToString()))
                        }));
                }, 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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(id.ToString()),
                        new NavigationPathSegment(navigationProperty))
                }));
                }, 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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(id.ToString()),
                        new NavigationPathSegment(navigationProperty))
                }));
                }, 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 EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(id.ToString()),
                        new NavigationPathSegment(navigationProperty))
                }));
                }, true);

            return modelBuilder.GetEdmModel();
        }
Esempio n. 47
0
        /// <summary>
        /// Generates a model explicitly.
        /// </summary>
        static IEdmModel GetExplicitEdmModel()
        {
            ODataModelBuilder modelBuilder = new ODataModelBuilder();

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

            products.HasIdLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4))));
                },
                followsConventions: true);

            products.HasEditLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4))));
                },
                followsConventions: true);

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

            suppliers.HasIdLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4))));
                },
                followsConventions: true);

            suppliers.HasEditLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4))));
                },
                followsConventions: true);

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

            families.HasIdLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4))));
                },
                followsConventions: true);

            families.HasEditLink(
                entityContext =>
                {
                    object id;
                    entityContext.EdmObject.TryGetPropertyValue("Id", out id);
                    return new Uri(entityContext.Url.CreateODataLink(
                                    new EntitySetPathSegment(entityContext.NavigationSource.Name),
                                    new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4)))
                                    );
                },
                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.EntityType<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.CreateODataLink(
                        new EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4)),
                        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.CreateODataLink(
                        new EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4)),
                        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.CreateODataLink(
                        new EntitySetPathSegment(entityContext.NavigationSource.Name),
                        new KeyValuePathSegment(ODataUriUtils.ConvertToUriLiteral(id, ODataVersion.V4)),
                        new NavigationPathSegment(navigationProperty.Name)));
                },
                followsConventions: true);

            ActionConfiguration createProduct = productFamily.Action("CreateProduct");
            createProduct.Parameter<string>("Name");
            createProduct.Returns<int>();

            modelBuilder.Namespace = typeof (ProductFamily).Namespace;
            return modelBuilder.GetEdmModel();
        }
Esempio n. 48
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;
        }
Esempio n. 49
0
        public static IEdmModel GetEdmModel()
        {
            if (_model == null)
            {
                ODataModelBuilder model = new ODataModelBuilder();

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

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

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

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

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

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

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

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

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

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

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

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

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

                _model = model.GetEdmModel();
            }

            return _model;
        }
Esempio n. 50
0
        public void ODataModelBuilder_Throws_AddCollectionOfEnumPropertyWithoutEnumType()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var complexTypeConfiguration = builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            complexTypeConfiguration.CollectionProperty(c => c.Colors);

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => builder.GetServiceModel(),
                "The enum type 'Color' does not exist.");
        }
Esempio n. 51
0
        public void PassNotEnumPropertyoStructuralTypeConfigurationAddEnumPropertyShouldThrowException()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            builder.ComplexType<EntityTypeWithEnumTypePropertyTestModel>();
            StructuralTypeConfiguration structuralTypeConfiguration = builder.StructuralTypes.Single();
            Expression<Func<EntityTypeWithEnumTypePropertyTestModel, int>> propertyExpression = e => e.ID;
            PropertyInfo propertyInfo = PropertySelectorVisitor.GetSelectedProperty(propertyExpression);

            // Act & Assert
            Assert.ThrowsArgument(
                () => structuralTypeConfiguration.AddEnumProperty(propertyInfo),
                "propertyInfo",
                "The property 'ID' on type 'System.Web.OData.Builder.EntityTypeWithEnumTypePropertyTestModel' must be an Enum property.");
        }
Esempio n. 52
0
        public void PassNotExistingPropertyoStructuralTypeConfigurationAddEnumPropertyShouldThrowException()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            StructuralTypeConfiguration structuralTypeConfiguration = builder.StructuralTypes.Single();
            Expression<Func<EntityTypeWithEnumTypePropertyTestModel, Color>> propertyExpression = e => e.RequiredColor;
            PropertyInfo propertyInfo = PropertySelectorVisitor.GetSelectedProperty(propertyExpression);

            // Act & Assert
            Assert.ThrowsArgument(
                () => structuralTypeConfiguration.AddEnumProperty(propertyInfo),
                "propertyInfo",
                "The property 'RequiredColor' does not belong to the type 'System.Web.OData.Builder.ComplexTypeWithEnumTypePropertyTestModel'.");
        }
Esempio n. 53
0
        public void PassNullToStructuralTypeConfigurationAddEnumPropertyShouldThrowException()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            StructuralTypeConfiguration structuralTypeConfiguration = builder.StructuralTypes.Single();

            // Act & Assert
            Assert.ThrowsArgumentNull(
                () => structuralTypeConfiguration.AddEnumProperty(null),
                "propertyInfo");
        }
Esempio n. 54
0
        public void PamameterOfEnumPropertyIsNotEnumShouldThrowException()
        {
            // Arrange
            var builder = new ODataModelBuilder();
            var color = builder.EnumType<Color>();
            color.Member(Color.Red);
            color.Member(Color.Green);
            color.Member(Color.Blue);
            var entityTypeConfiguration = builder.ComplexType<EntityTypeWithEnumTypePropertyTestModel>();

            // Act & Assert
            Assert.ThrowsArgument(
                () => entityTypeConfiguration.EnumProperty(e => e.ID),
                "propertyInfo",
                "The property 'ID' on type 'System.Web.OData.Builder.EntityTypeWithEnumTypePropertyTestModel' must be an Enum property.");
        }
Esempio n. 55
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;
        }
Esempio n. 56
0
        public void CreateCollectionOfEnumTypeProperty()
        {
            // Arrange
            var builder = new ODataModelBuilder().Add_Color_EnumType();
            var complexTypeConfiguration = builder.ComplexType<ComplexTypeWithEnumTypePropertyTestModel>();
            complexTypeConfiguration.CollectionProperty(c => c.Colors);

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

            // Assert
            Assert.Equal(1, complexType.Properties().Count());
            var colors = complexType.Properties().SingleOrDefault(p => p.Name == "Colors");
            Assert.NotNull(colors);
            Assert.True(colors.Type.IsCollection());
            Assert.True(((IEdmCollectionTypeReference)colors.Type).ElementType().IsEnum());
        }
        public void NonNullablePropertiesAreNotOptional()
        {
            // NOTE: Converting this to be a data driven test is painful as we need to mock C# overload resolution algorithm.
            var builder = new ODataModelBuilder();
            var complexType = builder.ComplexType<ComplexTypeTestModel>();

            Assert.False(complexType.Property(t => t.BoolProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.ByteProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.DateTimeOffsetProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.DateTimeProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.DoubleProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.GuidProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.IntProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.LongProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.ShortProperty).OptionalProperty);
            Assert.False(complexType.Property(t => t.TimeSpanProperty).OptionalProperty);
        }
        public void GetEdmModel_PropertyWithDatabaseAttribute_CannotSetStoreGeneratedPatternOnComplexType()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();
            builder.ComplexType<Customer>().Property(c => c.Name).HasStoreGeneratedPattern(DatabaseGeneratedOption.Computed);

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

            // Assert
            IEdmComplexType type = model.AssertHasComplexType(typeof(Customer));
            IEdmStructuralProperty property = type.AssertHasPrimitiveProperty(model, "Name", EdmPrimitiveTypeKind.String, isNullable: true);
            var idAnnotation = model.GetAnnotationValue<EdmStringConstant>(
                property,
                StoreGeneratedPatternAnnotation.AnnotationsNamespace,
                StoreGeneratedPatternAnnotation.AnnotationName);
            Assert.Null(idAnnotation);
        }
        public void NullablePropertiesAreOptional()
        {
            // NOTE: Converting this to be a data driven test is painful as we need to mock C# overload resolution algorithm.
            var builder = new ODataModelBuilder();
            var complexType = builder.ComplexType<ComplexTypeTestModel>();

            Assert.True(complexType.Property(t => t.NullableBoolProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableByteProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableDateTimeOffsetProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableDateTimeProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableDoubleProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableGuidProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableIntProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableLongProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableShortProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.NullableTimeSpanProperty).OptionalProperty);

            // Assert.True(complexType.Property(t => t.StreamProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.StringProperty).OptionalProperty);
            Assert.True(complexType.Property(t => t.ByteArrayProperty).OptionalProperty);
        }
Esempio n. 60
0
        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;
        }