public static IEdmModel AddEntitySet(this ODataConventionModelBuilder builder) { builder.AddEntitySet <Country>(); builder.AddEntitySet <UnitContact>(); builder.AddEntitySet <Contact>(); builder.AddEntitySet <Unit>(); builder.AddEntitySet <UnitListApiModel>(); return(builder.GetEdmModel()); }
public void GenerateNavigationLink_GeneratesLink() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order))); IEdmModel model = builder.GetEdmModel(); var edmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); configuration.EnableOData(model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); Uri uri = NavigationLinksGenerationConvention.GenerateNavigationPropertyLink( new EntityInstanceContext { EdmModel = model, EntityInstance = new NavigationLinksGenerationConventionTest_Order { ID = 100 }, EntitySet = edmEntitySet, EntityType = edmEntitySet.ElementType, UrlHelper = request.GetUrlHelper(), PathHandler = new DefaultODataPathHandler(model) }, edmEntitySet.ElementType.NavigationProperties().Single(), orders, includeCast: false); Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri); }
public IEdmModel GetEdmModel() { var builder = new ODataConventionModelBuilder { Namespace = typeof(Customer).Namespace }; // Nicer syntax... // //_modelBuilder // .AddEntitySet<Customer>() // .AddEntitySet<Order>() // ; foreach (var modelType in new [] { typeof(Customer), typeof(Order) }) { var entityType = builder.AddEntityType(modelType); builder.AddEntitySet(string.Format("{0}s", modelType.Name), entityType); } // Add TopBuyer Function to the Customer collection builder .EntityType <Customer>() .Collection .Function("TopBuyer") .ReturnsFromEntitySet <Customer>("Customers"); return(builder.GetEdmModel()); }
public void CanBuildModelForAnonymousTypes() { Type entityType = new { ID = default(int), ComplexCollection = new[] { new { ComplexProperty = default(string) } }, NavigationCollection = new[] { new { ID = default(int) } } }.GetType(); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.AddEntitySet("entityset", builder.AddEntity(entityType)); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntitySet("entityset", entityType); entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32); entity.AssertHasCollectionProperty(model, "ComplexCollection", new { ComplexProperty = default(string) }.GetType(), isNullable: true); entity.AssertHasNavigationProperty(model, "NavigationCollection", new { ID = default(int) }.GetType(), isNullable: false, multiplicity: EdmMultiplicity.ZeroOrOne); IEdmComplexType complexType = model.AssertHasComplexType(new { ComplexProperty = default(string) }.GetType()); complexType.AssertHasPrimitiveProperty(model, "ComplexProperty", EdmPrimitiveTypeKind.String, isNullable: true); }
private static IEdmModel GetEdmModel(Type type) { var builder = new ODataConventionModelBuilder(); builder.AddEntitySet(type.Name + "s", builder.AddEntityType(type)); return(builder.GetEdmModel()); }
public void ModelBuilder_DerivedComplexTypeHavingKeys_Throws() { MockType baseComplexType = new MockType("BaseComplexType"); MockType derivedComplexType = new MockType("DerivedComplexType") .Property(typeof(int), "DerivedComplexTypeId") .BaseType(baseComplexType); MockType entityType = new MockType("EntityType") .Property(typeof(int), "ID") .Property(baseComplexType.Object, "ComplexProperty"); MockAssembly assembly = new MockAssembly(baseComplexType, derivedComplexType, entityType); HttpConfiguration configuration = new HttpConfiguration(); configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(assembly)); var builder = new ODataConventionModelBuilder(configuration); builder.AddEntitySet("entities", builder.AddEntity(entityType)); Assert.Throws <InvalidOperationException>( () => builder.GetEdmModel(), "Cannot define keys on type 'DefaultNamespace.DerivedComplexType' deriving from 'DefaultNamespace.BaseComplexType'. Only the root type in the entity inheritance hierarchy can contain keys."); }
public void ModelBuilder_DerivedComplexTypeHavingKeys_SuccedsIfToldToBeComplex() { MockType baseComplexType = new MockType("BaseComplexType"); MockType derivedComplexType = new MockType("DerivedComplexType") .Property(typeof(int), "DerivedComplexTypeId") .BaseType(baseComplexType); MockType entityType = new MockType("EntityType") .Property(typeof(int), "ID") .Property(baseComplexType.Object, "ComplexProperty"); MockAssembly assembly = new MockAssembly(baseComplexType, derivedComplexType, entityType); HttpConfiguration configuration = new HttpConfiguration(); configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(assembly)); var builder = new ODataConventionModelBuilder(configuration); builder.AddEntitySet("entities", builder.AddEntity(entityType)); builder.AddComplexType(baseComplexType); IEdmModel model = builder.GetEdmModel(); Assert.Equal(3, model.SchemaElements.Count()); Assert.NotNull(model.FindType("DefaultNamespace.EntityType")); Assert.NotNull(model.FindType("DefaultNamespace.BaseComplexType")); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider) { app.UseCors("AllowAll"); var builder = new ODataConventionModelBuilder(serviceProvider); builder.EnableLowerCamelCase(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHangfireDashboard(); app.UseHttpsRedirection(); app.UseAuthentication(); app.UseMvc(routeBuilder => { routeBuilder.MapODataServiceRoute("ftapi", "ftapi", builder.AddEntitySet()); routeBuilder.Count().Filter().OrderBy().Expand().Select().MaxTop(null); routeBuilder.EnableDependencyInjection(); routeBuilder.MapRoute( name: "DefaultApi", template: "api/{controller}/{id?}" ); }); }
public void GenerateSelfLinkWithCast_Works() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var vehicles = builder.AddEntitySet("cars", builder.AddEntity(typeof(Car))); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet carsEdmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); string routeName = "Route"; configuration.Routes.MapODataRoute(routeName, null, model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.SetConfiguration(configuration); request.SetODataRouteName(routeName); string idLink = SelfLinksGenerationConvention.GenerateSelfLink( vehicles, new EntityInstanceContext() { EdmModel = model, EntitySet = carsEdmEntitySet, EntityType = carsEdmEntitySet.ElementType, Url = request.GetUrlHelper(), EntityInstance = new Car { Model = 2009, Name = "Accord" } }, includeCast: true); Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car", idLink); }
public void GenerateNavigationLink_GeneratesCorrectLink_EvenIfRouteDataPointsToADifferentController() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order))); IEdmModel model = builder.GetEdmModel(); var edmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); var route = configuration.Routes.MapHttpRoute(ODataRouteNames.PropertyNavigation, "{controller}({parentId})/{navigationProperty}"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(route, new HttpRouteValueDictionary(new { controller = "Customers" })); Uri uri = NavigationLinksGenerationConvention.GenerateNavigationPropertyLink( new EntityInstanceContext { EdmModel = model, EntityInstance = new NavigationLinksGenerationConventionTest_Order { ID = 100 }, EntitySet = edmEntitySet, EntityType = edmEntitySet.ElementType, UrlHelper = request.GetUrlHelper() }, edmEntitySet.ElementType.NavigationProperties().Single(), orders, includeCast: false); Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri); }
public void GenerateSelfLinkWithoutCast_Works() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var vehicles = builder.AddEntitySet("cars", builder.AddEntity(typeof(Car))); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet carsEdmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); configuration.Routes.MapHttpRoute(ODataRouteNames.GetById, "{controller}({id})"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); Uri uri = SelfLinksGenerationConvention.GenerateSelfLink( vehicles, new EntityInstanceContext(model, carsEdmEntitySet, carsEdmEntitySet.ElementType, request.GetUrlHelper(), new Car { Model = 2009, Name = "Accord" }), includeCast: false); Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')", uri.AbsoluteUri); }
public void GenerateNavigationLink_GeneratesCorrectLink_EvenIfRouteDataPointsToADifferentController() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order))); IEdmModel model = builder.GetEdmModel(); var edmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); string routeName = "Route"; configuration.Routes.MapODataRoute(routeName, null, model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.SetConfiguration(configuration); request.SetODataRouteName(routeName); Uri uri = NavigationLinksGenerationConvention.GenerateNavigationPropertyLink( new EntityInstanceContext { EdmModel = model, EntityInstance = new NavigationLinksGenerationConventionTest_Order { ID = 100 }, EntitySet = edmEntitySet, EntityType = edmEntitySet.ElementType, Url = request.GetUrlHelper() }, edmEntitySet.ElementType.NavigationProperties().Single(), orders, includeCast: false); Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri); }
public void ConcurrencyCheckAttributeEdmPropertyConvention_DoesnotOverwriteExistingConfiguration() { // Arrange MockType type = new MockType("Entity") .Property(typeof(int), "ID") .Property(typeof(int), "Count", new ConcurrencyCheckAttribute()); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var entityType = builder.AddEntityType(type); entityType.AddProperty(type.GetProperty("Count")).IsOptional(); builder.AddEntitySet("EntitySet", entityType); // Act IEdmModel model = builder.GetEdmModel(); // Assert IEdmEntityType entity = model.AssertHasEntityType(type); IEdmStructuralProperty property = entity.AssertHasPrimitiveProperty( model, "Count", EdmPrimitiveTypeKind.Int32, isNullable: true); IEdmEntitySet entitySet = model.EntityContainer.FindEntitySet("EntitySet"); Assert.NotNull(entitySet); IEnumerable <IEdmStructuralProperty> currencyProperties = model.GetConcurrencyProperties(entitySet); IEdmStructuralProperty currencyProperty = Assert.Single(currencyProperties); Assert.Same(property, currencyProperty); }
internal static IEdmModel GetEdmModel(this HttpActionDescriptor actionDescriptor, Type entityClrType) { if (actionDescriptor == null) { throw Error.ArgumentNull("actionDescriptor"); } if (entityClrType == null) { throw Error.ArgumentNull("entityClrType"); } // save the EdmModel to the action descriptor return(actionDescriptor.Properties.GetOrAdd(ModelKeyPrefix + entityClrType.FullName, _ => { IAssembliesResolver resolver = actionDescriptor.Configuration.Services.GetAssembliesResolver(); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(new WebApiAssembliesResolver(resolver), isQueryCompositionMode: true); EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(entityClrType); builder.AddEntitySet(entityClrType.Name, entityTypeConfiguration); IEdmModel edmModel = builder.GetEdmModel(); Contract.Assert(edmModel != null); return edmModel; }) as IEdmModel); }
public override IEdmModel GetModel(Type elementClrType, HttpRequestMessage request, HttpActionDescriptor actionDescriptor) { // Get model for the request IEdmModel model = request.ODataProperties().Model; if (model == null) { // user has not configured anything or has registered a model without the element type // let's create one just for this type and cache it in the action descriptor model = actionDescriptor.Properties.GetOrAdd("System.Web.OData.Model+" + elementClrType.FullName, _ => { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(actionDescriptor.Configuration, isQueryCompositionMode: true); builder.EnableLowerCamelCase(); EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(elementClrType); builder.AddEntitySet(elementClrType.Name, entityTypeConfiguration); IEdmModel edmModel = builder.GetEdmModel(); Contract.Assert(edmModel != null); return edmModel; }) as IEdmModel; } Contract.Assert(model != null); return model; }
public void GenerateSelfLinkWithCast_Works() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var vehicles = builder.AddEntitySet("cars", builder.AddEntity(typeof(Car))); IEdmModel model = builder.GetEdmModel(); IEdmEntitySet carsEdmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); configuration.EnableOData(model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); Uri uri = SelfLinksGenerationConvention.GenerateSelfLink( vehicles, new EntityInstanceContext() { EdmModel = model, EntitySet = carsEdmEntitySet, EntityType = carsEdmEntitySet.ElementType, UrlHelper = request.GetUrlHelper(), PathHandler = new DefaultODataPathHandler(model), EntityInstance = new Car { Model = 2009, Name = "Accord" } }, includeCast: true); Assert.Equal("http://localhost/cars(Model=2009,Name='Accord')/System.Web.Http.OData.Builder.TestModels.Car", uri.AbsoluteUri); }
/// <summary> /// Get the OData metadata about the reliable collections from the reliable state manager using reflection. /// </summary> /// <param name="stateManager">Reliable state manager for the replica.</param> /// <returns>The OData metadata for this state manager.</returns> public static async Task <string> GetMetadataAsync(this IReliableStateManager stateManager) { // Build the OData model from the queryable types in the reliable state manager. var builder = new ODataConventionModelBuilder(); foreach (var queryable in await stateManager.GetQueryableTypes().ConfigureAwait(false)) { var qkey = queryable.Key; var qkey2 = qkey.Replace('.', '#'); Console.WriteLine(qkey2); dictEntityMap.Add(queryable.Key, qkey2); var entity = builder.AddEntity(queryable.Value); builder.AddEntitySet(qkey2, entity); } var model = builder.GetEdmModel(); // Write the OData metadata document. using (var stream = new MemoryStream()) using (var message = new InMemoryMessage { Stream = stream }) { var settings = new ODataMessageWriterSettings(); var writer = new ODataMessageWriter((IODataResponseMessage)message, settings, model); writer.WriteMetadataDocument(); return(Encoding.UTF8.GetString(stream.ToArray())); } }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); loggerFactory.AddDebug(); Action <IRouteBuilder> configureRoutes = routeBuilder => { foreach (var Connection in this.Connections) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(app.ApplicationServices); var entrys = _entrys[Connection.Key]; foreach (Entry entry in entrys) { var entityType = builder.AddEntityType(entry.Type); var entirySet = builder.AddEntitySet(entry.Type.Name, entityType); } var edmModel = builder.GetEdmModel(); routeBuilder.MapODataServiceRoute($"ODATAROUTE_{Connection.Key}", Connection.Key, edmModel); } routeBuilder .Count() .Filter() .OrderBy() .Expand() .Select() .MaxTop(null); routeBuilder.EnableDependencyInjection(); }; app.UseMvc(configureRoutes); app.UseDeveloperExceptionPage(); }
public IODataApiBuilder AddResource(Type type, string customRoute = null) { var route = customRoute ?? type.Name.ToLower(); _metadata.Add(new EntityMetadata(type, route)); var entityType = _modelBuilder.AddEntityType(type); _modelBuilder.AddEntitySet(route, entityType); return(this); }
/// <summary> /// Registers a product model builder to provide a model for products /// </summary> /// <typeparam name="TBuilder"></typeparam> /// <param name="name">This is the odata endpoint name for this model. You will be able to access this model at /odata/<name></param> /// <param name="builder"></param> /// <returns></returns> public WebApiConfiguration WithProductModel <TBuilder>(string name, TBuilder builder) where TBuilder : IProductModelBuilder { ODataProductsController.Builders.Add(name, builder); EntityTypeConfiguration entity = _odataBuilder.AddEntityType(builder.ModelType); _odataBuilder.AddEntitySet(name, entity); _productModels.Add(name); return(this); }
internal static IEdmModel GetEdmModel(this HttpActionDescriptor actionDescriptor, Type entityClrType) { // save the EdmModel to the action descriptor return(actionDescriptor.Properties.GetOrAdd(EdmModelKey + entityClrType.FullName, _ => { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(actionDescriptor.Configuration, isQueryCompositionMode: true); EntityTypeConfiguration entityTypeConfiguration = builder.AddEntity(entityClrType); builder.AddEntitySet(entityClrType.Name, entityTypeConfiguration); IEdmModel edmModel = builder.GetEdmModel(); return edmModel; }) as IEdmModel); }
public static void ClassInitialize(TestContext testContext) { var builder = new ODataConventionModelBuilder(); var type = typeof(MockOpenType); var entityTypeConfiguration = builder.AddEntityType(type); entityTypeConfiguration.HasKey(type.GetProperty("Id")); builder.AddEntitySet(type.Name, entityTypeConfiguration); var edmModels = builder.GetEdmModel(); oDataQueryContext = new ODataQueryContext(edmModels, type, new ODataPath()); }
public static IEdmModel GetEdmModel(HttpConfiguration configuration) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(configuration); foreach (var type in Creator.EntityTypes) { var entity = builder.AddEntity(type); builder.AddEntitySet(type.Name, entity); } return(builder.GetEdmModel()); }
/// <summary> /// Add given all given <see cref="Type"/> objects with a Id Property to the <see cref="ODataConventionModelBuilder"/> list of <see cref="EntitySetConfiguration"/> /// </summary> /// <param name="odataModelBuilder">the <see cref="ODataConventionModelBuilder"/> instance used to build the odata conventions</param> /// <param name="types">the given types to be mapped and added to the <see cref="EntitySetConfiguration"/> collection</param> /// <returns>the given instance of <see cref="ODataConventionModelBuilder"/> with a <see cref="EntitySetConfiguration"/> item for each <see cref="Type"/> given</returns> public static ODataConventionModelBuilder AddTypesToOdataEntitySet(this ODataConventionModelBuilder odataModelBuilder, params Type[] types) { foreach (var type in types) { if (!type.GetProperties().Any(d => d.Name == "Id")) { continue; } odataModelBuilder.AddEntitySet(type.Name, odataModelBuilder.AddEntityType(type)); } odataModelBuilder.ModelAliasingEnabled = true; return(odataModelBuilder); }
private IEdmModel GetEdmModel() { var builder = new ODataConventionModelBuilder(); var types = Assembly.GetExecutingAssembly().GetTypes().Where(t => t.GetInterfaces().Contains(typeof(IGenericODataModel))).ToList(); foreach (Type type in types) { var entityTypeConfig = builder.AddEntityType(type); builder.AddEntitySet(type.Name, entityTypeConfig); } return(builder.GetEdmModel()); }
public static IEdmModel GetEdmModel(IServiceProvider servicePrivider) { var builder = new ODataConventionModelBuilder(servicePrivider); var entitySets = typeof(AppDbContext).GetProperties().Where(x => x.MemberType == System.Reflection.MemberTypes.Property && x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(DbSet <>)).ToList(); foreach (var entitySet in entitySets) { Type type = entitySet.PropertyType.GenericTypeArguments.First(); EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(type); builder.AddEntitySet(entitySet.Name, entityTypeConfiguration); } return(builder.GetEdmModel()); }
public static IEdmModel BuildEdmModel(Type ApiContextType) { ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.Namespace = ApiContextType.Namespace; var publicProperties = ApiContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in publicProperties) { var entityClrType = TypeHelper.GetImplementedIEnumerableType(property.PropertyType); EntityTypeConfiguration entity = builder.AddEntityType(entityClrType); builder.AddEntitySet(property.Name, entity); } return builder.GetEdmModel(); }
public static IEdmModel GetEdmModel() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var types = typeof(EntityBase).Assembly.GetTypes(); foreach (var type in types) { if (type.BaseType == typeof(EntityBase) && type.GetCustomAttribute <AutoGeneratedOdataControllerAttribute>() is AutoGeneratedOdataControllerAttribute) { builder.AddEntitySet(type.Name, builder.AddEntityType(type)); } } return(builder.GetEdmModel()); }
public static void ClassInitialize(TestContext testContext) { var builder = new ODataConventionModelBuilder(); var type = typeof(MockOpenType); var entityTypeConfiguration = builder.AddEntityType(type); entityTypeConfiguration.HasKey(type.GetProperty("Id")); builder.AddEntitySet(type.Name, entityTypeConfiguration); var conf = builder.EntitySet <MockOpenType>(type.Name); conf.EntityType.Property(p => p.Id).Name = "id"; var edmModels = builder.GetEdmModel(); ODataQueryContext = new ODataQueryContext(edmModels, type, new ODataPath()); var collection = new ServiceCollection(); #if NET6_0 collection .AddControllers() .AddOData(); #else collection.AddOData(); #endif collection.AddODataQueryFilter(); collection.AddTransient <ODataUriResolver>(); collection.AddTransient <ODataQueryValidator>(); collection.AddTransient <TopQueryValidator>(); collection.AddTransient <FilterQueryValidator>(); collection.AddTransient <SkipQueryValidator>(); collection.AddTransient <OrderByQueryValidator>(); #if NET6_0 collection.AddTransient <ILoggerFactory, TestLoggingFactory>(); #endif Provider = collection.BuildServiceProvider(); var applicationBuilder = Substitute.For <IApplicationBuilder>(); applicationBuilder.ApplicationServices.Returns(Provider); #if !NET6_0 var routeBuilder = new RouteBuilder(applicationBuilder); routeBuilder.EnableDependencyInjection(); #endif }
private static IEdmModel CreateImplicitModel(HttpConfiguration configuration, Type elementClrType) { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(configuration, isQueryCompositionMode: true); // Add the type to the model as an entity and add an entity set with the same name. EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(elementClrType); builder.AddEntitySet(elementClrType.Name, entityTypeConfiguration); // Build the model and add the AuthorizedRolesAnnotation. IEdmModel edmModel = builder.GetEdmModel(); Contract.Assert(edmModel != null); edmModel.AddAuthorizedRolesAnnotations(); return edmModel; }
private static IEdmModel GetEdmModel() { var builder = new ODataConventionModelBuilder(); var modelsAssembly = typeof(Person).Assembly; var types = DatabaseHelper.GetEntityTypes(modelsAssembly) .Union(DatabaseHelper.GetViewTypes(modelsAssembly)); foreach (var type in types) { var entityType = builder.AddEntityType(type); var configuration = builder.AddEntitySet(type.Name, entityType); } return(builder.GetEdmModel()); }
private static IEdmModel GetEdmModel(Assembly asm, Action <ODataConventionModelBuilder> modelBuilder = null) { var builder = new ODataConventionModelBuilder(); var classes = asm.DefinedTypes.Where(t => t.BaseType?.Name == typeof(BaseController <>).Name); foreach (var @class in classes) { var type = @class.BaseType?.GenericTypeArguments[0]; builder.AddEntitySet(GetControllerNameFromType(@class.Name), builder.AddEntityType(type)); } modelBuilder?.Invoke(builder); return(builder.GetEdmModel()); }
public static IEdmModel BuildEdmModel(Type ApiContextType) { ODataModelBuilder builder = new ODataConventionModelBuilder(); builder.Namespace = ApiContextType.Namespace; var publicProperties = ApiContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in publicProperties) { var entityClrType = TypeHelper.GetImplementedIEnumerableType(property.PropertyType); EntityTypeConfiguration entity = builder.AddEntityType(entityClrType); builder.AddEntitySet(property.Name, entity); } return(builder.GetEdmModel()); }
public static IEdmModel BuildEdmModel(Type apiContextType, AssembliesResolver assembliesResolver, Action<ODataConventionModelBuilder> after = null) { var builder = new ODataConventionModelBuilder(assembliesResolver) { Namespace = apiContextType.Namespace }; var publicProperties = apiContextType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var property in publicProperties) { var entityClrType = TypeHelper.GetImplementedIEnumerableType(property.PropertyType); var entity = builder.AddEntityType(entityClrType); builder.AddEntitySet(property.Name, entity); } after?.Invoke(builder); var edmModel = builder.GetEdmModel(); return edmModel; }
private static ODataConventionModelBuilder MapAllODataModels(string namespaceForTypes) { var builder = new ODataConventionModelBuilder(); var types = Assembly.GetExecutingAssembly() .GetTypes() .Where(x => string.Equals(x.Namespace, namespaceForTypes, StringComparison.Ordinal)); foreach (var type in types) { var name = type.GetCustomAttribute(typeof (ApiMapNameAttribute)) as ApiMapNameAttribute; if (name == null) continue; var entityType = builder.AddEntityType(type); builder.AddEntitySet(name.Name, entityType); } return builder; }
internal static IEdmModel GetEdmModel(this HttpActionDescriptor actionDescriptor, Type entityClrType) { if (actionDescriptor == null) { throw Error.ArgumentNull("actionDescriptor"); } if (entityClrType == null) { throw Error.ArgumentNull("entityClrType"); } // save the EdmModel to the action descriptor return actionDescriptor.Properties.GetOrAdd(ModelKeyPrefix + entityClrType.FullName, _ => { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(actionDescriptor.Configuration, isQueryCompositionMode: true); EntityTypeConfiguration entityTypeConfiguration = builder.AddEntityType(entityClrType); builder.AddEntitySet(entityClrType.Name, entityTypeConfiguration); IEdmModel edmModel = builder.GetEdmModel(); Contract.Assert(edmModel != null); return edmModel; }) as IEdmModel; }
public void OnModelCreating_IsInvoked_AfterConventionsAreRun() { // Arrange MockType entity = new MockType("entity") .Property<int>("ID"); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.AddEntitySet("entities", builder.AddEntity(entity)); builder.OnModelCreating = (modelBuilder) => { var entityConfiguration = modelBuilder.StructuralTypes.OfType<EntityTypeConfiguration>().Single(); Assert.Equal(1, entityConfiguration.Keys.Count()); var key = entityConfiguration.Keys.Single(); Assert.Equal("ID", key.Name); // mark the key as optional just to verify later. key.OptionalProperty = true; }; // Act IEdmModel model = builder.GetEdmModel(); // Assert Assert.True(model.SchemaElements.OfType<IEdmEntityType>().Single().Key().Single().Type.IsNullable); }
public void GenerateNavigationLink_GeneratesCorrectLink_EvenIfRouteDataPointsToADifferentController() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order))); IEdmModel model = builder.GetEdmModel(); var edmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); configuration.EnableOData(model); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute(), new HttpRouteValueDictionary(new { controller = "Customers" })); Uri uri = NavigationLinksGenerationConvention.GenerateNavigationPropertyLink( new EntityInstanceContext { EdmModel = model, EntityInstance = new NavigationLinksGenerationConventionTest_Order { ID = 100 }, EntitySet = edmEntitySet, EntityType = edmEntitySet.ElementType, PathHandler = new DefaultODataPathHandler(model), UrlHelper = request.GetUrlHelper() }, edmEntitySet.ElementType.NavigationProperties().Single(), orders, includeCast: false); Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri); }
public void ObjectCollectionsAreIgnoredByDefault(Type propertyType) { MockType type = new MockType("entity") .Property<int>("ID") .Property(propertyType, "Collection"); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var entityType = builder.AddEntity(type); builder.AddEntitySet("entityset", entityType); IEdmModel model = builder.GetEdmModel(); Assert.Equal(2, model.SchemaElements.Count()); var entityEdmType = model.AssertHasEntitySet("entityset", type); }
public void CanBuildModelForAnonymousTypes() { Type entityType = new { ID = default(int), NavigationCollection = new[] { new { ID = default(int) } } }.GetType(); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(new HttpConfiguration(), isQueryCompositionMode: true); builder.AddEntitySet("entityset", builder.AddEntity(entityType)); IEdmModel model = builder.GetEdmModel(); IEdmEntityType entity = model.AssertHasEntitySet("entityset", entityType); entity.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32); entity.AssertHasNavigationProperty(model, "NavigationCollection", new { ID = default(int) }.GetType(), isNullable: false, multiplicity: EdmMultiplicity.Many); }
//----------------------------------------------------------------------------------------------------------------------------------------------------- private IEdmModel BuildEdmModel() { var modelBuilder = new ODataConventionModelBuilder(); foreach ( var entityType in _repository.GetEntityTypesInRepository() ) { modelBuilder.AddEntitySet(entityType.Name, modelBuilder.AddEntityType(entityType)); var structuralType = modelBuilder.StructuralTypes.First(t => t.ClrType == entityType); foreach ( var utcProperty in entityType.GetProperties().Where(p => p.PropertyType == typeof(DateTimeOffset)) ) { structuralType.AddProperty(utcProperty); } foreach ( var nonUtcProperty in entityType.GetProperties().Where(p => p.PropertyType == typeof(DateTime)) ) { structuralType.RemoveProperty(nonUtcProperty); } } return modelBuilder.GetEdmModel(); }
public void GenerateNavigationLink_GeneratesLink() { ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var orders = builder.AddEntitySet("Orders", builder.AddEntity(typeof(NavigationLinksGenerationConventionTest_Order))); IEdmModel model = builder.GetEdmModel(); var edmEntitySet = model.EntityContainers().Single().EntitySets().Single(); HttpConfiguration configuration = new HttpConfiguration(); var route = configuration.Routes.MapHttpRoute(ODataRouteNames.PropertyNavigation, "{controller}({parentId})/{navigationProperty}"); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://localhost"); request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = new HttpRouteData(new HttpRoute()); Uri uri = NavigationLinksGenerationConvention.GenerateNavigationPropertyLink( new EntityInstanceContext { EdmModel = model, EntityInstance = new NavigationLinksGenerationConventionTest_Order { ID = 100 }, EntitySet = edmEntitySet, EntityType = edmEntitySet.ElementType, UrlHelper = request.GetUrlHelper() }, edmEntitySet.ElementType.NavigationProperties().Single(), orders, includeCast: false); Assert.Equal("http://localhost/Orders(100)/Customer", uri.AbsoluteUri); }
public void CanMapObjectArrayAsAComplexProperty() { MockType type = new MockType("entity") .Property<int>("ID") .Property<object[]>("Collection"); ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); var entityType = builder.AddEntity(type); entityType.AddCollectionProperty(type.GetProperty("Collection")); builder.AddEntitySet("entityset", entityType); IEdmModel model = builder.GetEdmModel(); Assert.Equal(3, model.SchemaElements.Count()); var entityEdmType = model.AssertHasEntitySet("entityset", type); model.AssertHasComplexType(typeof(object)); entityEdmType.AssertHasCollectionProperty(model, "Collection", typeof(object), isNullable: true); }
public void ApplyTo_Picks_DefaultOrder(string oDataQuery, Type elementType, string expectedExpression) { IQueryable query = Array.CreateInstance(elementType, 0).AsQueryable(); var modelBuilder = new ODataConventionModelBuilder(); modelBuilder.AddEntitySet("entityset", modelBuilder.AddEntity(elementType)); var model = modelBuilder.GetEdmModel(); var message = new HttpRequestMessage( HttpMethod.Get, new Uri("http://server/service/entityset?" + oDataQuery) ); var options = new ODataQueryOptions(new ODataQueryContext(model, elementType), message); IQueryable finalQuery = options.ApplyTo(query); string queryExpression = ExpressionStringBuilder.ToString(finalQuery.Expression); queryExpression = queryExpression.Substring(queryExpression.IndexOf("OrderBy")); Assert.Equal(queryExpression, expectedExpression); }
public void DerivedTypes_Can_DefineKeys_InQueryCompositionMode() { // Arrange MockType baseType = new MockType("BaseType") .Property(typeof(int), "ID"); MockType derivedType = new MockType("DerivedType") .Property(typeof(int), "DerivedTypeId") .BaseType(baseType); MockAssembly assembly = new MockAssembly(baseType, derivedType); HttpConfiguration configuration = new HttpConfiguration(); configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(assembly)); var builder = new ODataConventionModelBuilder(configuration, isQueryCompositionMode: true); builder.AddEntitySet("bases", builder.AddEntity(baseType)); // Act IEdmModel model = builder.GetEdmModel(); // Assert model.AssertHasEntitySet("bases", baseType); IEdmEntityType baseEntityType = model.AssertHasEntityType(baseType); IEdmEntityType derivedEntityType = model.AssertHasEntityType(derivedType, baseType); baseEntityType.AssertHasKey(model, "ID", EdmPrimitiveTypeKind.Int32); derivedEntityType.AssertHasPrimitiveProperty(model, "DerivedTypeId", EdmPrimitiveTypeKind.Int32, isNullable: false); }
public void ModelBuilder_DerivedComplexTypeHavingKeys_Throws() { MockType baseComplexType = new MockType("BaseComplexType"); MockType derivedComplexType = new MockType("DerivedComplexType") .Property(typeof(int), "DerivedComplexTypeId") .BaseType(baseComplexType); MockType entityType = new MockType("EntityType") .Property(typeof(int), "ID") .Property(baseComplexType.Object, "ComplexProperty"); MockAssembly assembly = new MockAssembly(baseComplexType, derivedComplexType, entityType); HttpConfiguration configuration = new HttpConfiguration(); configuration.Services.Replace(typeof(IAssembliesResolver), new TestAssemblyResolver(assembly)); var builder = new ODataConventionModelBuilder(configuration); builder.AddEntitySet("entities", builder.AddEntity(entityType)); Assert.Throws<InvalidOperationException>( () => builder.GetEdmModel(), "Cannot define keys on type 'DefaultNamespace.DerivedComplexType' deriving from 'DefaultNamespace.BaseComplexType'. Only the root type in the entity inheritance hierarchy can contain keys."); }