• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# ODataQueryOptions类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中ODataQueryOptions的典型用法代码示例。如果您正苦于以下问题:C# ODataQueryOptions类的具体用法?C# ODataQueryOptions怎么用?C# ODataQueryOptions使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ODataQueryOptions类属于命名空间,在下文中一共展示了ODataQueryOptions类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Get

 public IHttpActionResult Get(ODataQueryOptions<ODataQueryOptionTest_EntityModel> queryOptions)
 {
     // Don't apply Filter and Expand, but apply Select.
     var appliedQueryOptions = AllowedQueryOptions.Skip | AllowedQueryOptions.Filter | AllowedQueryOptions.Expand;
     var res = queryOptions.ApplyTo(_entityModels, appliedQueryOptions);
     return Ok(res.AsQueryable());
 }
开发者ID:genusP,项目名称:WebApi,代码行数:7,代码来源:ODataQueryOptionTest.cs


示例2: GetTeams

        public IQueryable<Team> GetTeams(ODataQueryOptions queryOptions)
        {
            // Validate query options
            var settings = new ODataValidationSettings()
            {
                MaxTop = 400
            };
            queryOptions.Validate(settings);

            // Apply the filter before going through to check if links exist for significant performance improvements
            var teams = (IQueryable<Team>)queryOptions.ApplyTo(Db.core.Teams);

            // RouteLinker creates Uris for actions
            var linker = new RouteLinker(Request);

            foreach (var team in teams)
            {
                if (team.Links == null)
                {
                    team.Links = new SerializableDynamic();
                    team.Links.url = linker.GetUri<TeamsController>(c => c.GetTeam(team.Number)).ToString();
                }
            }

            var nextRequest = Request.RequestUri;

            return Db.core.Teams.AsQueryable();
        }
开发者ID:vexteamnet,项目名称:ApiApp,代码行数:28,代码来源:TeamsController.cs


示例3: Get

 public IHttpActionResult Get(int key, ODataQueryOptions<Customer> options)
 {
     IQueryable<Customer> customerByIdQuery = _context.Customers.Where(c => c.Id == key);
     if (options.IfNoneMatch != null)
     {
         IQueryable<Customer> customerQuery = options.IfNoneMatch.ApplyTo(customerByIdQuery) as IQueryable<Customer>;
         if (!customerQuery.Any())
         {
             // The entity has the same ETag as the one in the If-None-Match header of the request,
             // so it hasn't been modified since it was retrieved the first time.
             return StatusCode(HttpStatusCode.NotModified);
         }
         else
         {
             // The entity has a different ETag than the one specified in the If-None-Match header of the request,
             // so we return the entity.
             return Ok(SingleResult<Customer>.Create(customerByIdQuery));
         }
     }
     else
     {
         // The request didn't contain any ETag, so we return the entity.
         return Ok(SingleResult<Customer>.Create(customerByIdQuery));
     }
 }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:25,代码来源:CustomersController.cs


示例4: GetFromManager

        // Pass ODataQueryOptions as parameter, and call validation manually
        public IHttpActionResult GetFromManager(ODataQueryOptions<Manager> queryOptions)
        {
            if (queryOptions.SelectExpand != null)
            {
                queryOptions.SelectExpand.LevelsMaxLiteralExpansionDepth = 5;
            }

            var validationSettings = new ODataValidationSettings { MaxExpansionDepth = 5 };

            try
            {
                queryOptions.Validate(validationSettings);
            }
            catch (ODataException e)
            {
                var responseMessage = new HttpResponseMessage(HttpStatusCode.BadRequest);
                responseMessage.Content = new StringContent(
                    string.Format("The query specified in the URI is not valid. {0}", e.Message));
                return ResponseMessage(responseMessage);
            }

            var querySettings = new ODataQuerySettings();
            var result = queryOptions.ApplyTo(_employees.OfType<Manager>().AsQueryable(), querySettings).AsQueryable();
            return Ok(result, result.GetType());
        }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:26,代码来源:EmployeesController.cs


示例5: Get

        public IHttpActionResult Get([FromODataUri] string key, ODataQueryOptions<Person> queryOptions)
        {
            IEnumerable<Person> appliedPeople = TripPinSvcDataSource.Instance.People.Where(item => item.UserName == key);

            if (appliedPeople.Count() == 0)
            {
                return NotFound();
            }

            // TODO : Bug https://aspnetwebstack.codeplex.com/workitem/2033, should get from ODataQueryOptions
            if (Request.Headers.IfNoneMatch.Count > 0)
            {
                if (Request.Headers.IfNoneMatch.ElementAt(0).Tag.Equals("*"))
                {
                    return StatusCode(HttpStatusCode.NotModified);
                }
                else
                {
                    appliedPeople = queryOptions.IfNoneMatch.ApplyTo(appliedPeople.AsQueryable()).Cast<Person>();
                }
            }

            if (appliedPeople.Count() == 0)
            {
                return StatusCode(HttpStatusCode.NotModified);
            }
            else
            {
                return Ok(appliedPeople.Single());
            }
        }
开发者ID:chinadragon0515,项目名称:ODataSamples,代码行数:31,代码来源:PeopleController.cs


示例6: Validate

        /// <summary>
        /// Validates the specified query options.
        /// </summary>
        /// <param name="queryOptions">The query options.</param>
        /// <param name="validationSettings">The validation settings.</param>
        /// <exception cref="ODataException">Thrown if the validation fails.</exception>
        internal static void Validate(ODataQueryOptions queryOptions, ODataValidationSettings validationSettings)
        {
            if (queryOptions.Filter != null)
            {
                if ((validationSettings.AllowedQueryOptions & AllowedQueryOptions.Filter) != AllowedQueryOptions.Filter)
                {
                    throw new ODataException(Messages.FilterQueryOptionNotSupported);
                }

                ValidateFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateStringFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateDateFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateMathFunctions(queryOptions.Filter.RawValue, validationSettings);
                ValidateLogicalOperators(queryOptions.Filter.RawValue, validationSettings);
                ValidateArithmeticOperators(queryOptions.Filter.RawValue, validationSettings);
            }

            if (queryOptions.RawValues.Expand != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Expand) != AllowedQueryOptions.Expand)
            {
                throw new ODataException(Messages.ExpandQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Format != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Format) != AllowedQueryOptions.Format)
            {
                throw new ODataException(Messages.FormatQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.InlineCount != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.InlineCount) != AllowedQueryOptions.InlineCount)
            {
                throw new ODataException(Messages.InlineCountQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.OrderBy != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.OrderBy) != AllowedQueryOptions.OrderBy)
            {
                throw new ODataException(Messages.OrderByQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Select != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Select) != AllowedQueryOptions.Select)
            {
                throw new ODataException(Messages.SelectQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Skip != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Skip) != AllowedQueryOptions.Skip)
            {
                throw new ODataException(Messages.SkipQueryOptionNotSupported);
            }

            if (queryOptions.RawValues.Top != null
                && (validationSettings.AllowedQueryOptions & AllowedQueryOptions.Top) != AllowedQueryOptions.Top)
            {
                throw new ODataException(Messages.TopQueryOptionNotSupported);
            }
        }
开发者ID:JulioGold,项目名称:Net.Http.WebApi.OData,代码行数:65,代码来源:ODataQueryOptionsValidator.cs


示例7: GetDiamondImport

        public IHttpActionResult GetDiamondImport(ODataQueryOptions<ProductDiamondImport> options)
        {
            var imports = this.database.DiamondImports.AsQueryable();
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("Products")) imports = imports.Include(s => s.Products);

            return Ok(imports);
        }
开发者ID:wei-zhou,项目名称:diamond,代码行数:8,代码来源:ProductController.cs


示例8: ValidateQuery

        // Override this method to plug in our custom validator.
        public override void ValidateQuery(HttpRequestMessage request, ODataQueryOptions queryOptions)
        {
            IEdmModel model = queryOptions.Context.Model;
            IPrincipal principal = request.GetRequestContext().Principal;

            queryOptions.Validator = new AuthorizedRolesQueryValidator(model, principal);
            base.ValidateQuery(request, queryOptions);
        }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:9,代码来源:AuthorizationEnableQueryAttribute.cs


示例9: ApplyQueryOptions

		public virtual object ApplyQueryOptions(object value, HttpRequest request, ActionDescriptor actionDescriptor, AssembliesResolver assembliesResolver)
		{
			var elementClrType = value is IEnumerable
				? TypeHelper.GetImplementedIEnumerableType(value.GetType())
				: value.GetType();

			var model = request.ODataProperties().Model;
			if (model == null)
			{
				throw Error.InvalidOperation(SRResources.QueryGetModelMustNotReturnNull);
			}

			var queryContext = new ODataQueryContext(
				model,
				elementClrType,
				assembliesResolver,
				request.ODataProperties().Path
				);

			var queryOptions = new ODataQueryOptions(queryContext, request, assembliesResolver);

			var enumerable = value as IEnumerable;
			if (enumerable == null)
			{
				// response is single entity.
				return value;
			}

			// response is a collection.
			var query = (value as IQueryable) ?? enumerable.AsQueryable();

			query = queryOptions.ApplyTo(query,
				new ODataQuerySettings
				{
					// TODO: If we are using SQL, set this to false
					// otherwise if it is entities in code then
					// set it to true
					HandleNullPropagation = 
					//HandleNullPropagationOption.True
					HandleNullPropagationOptionHelper.GetDefaultHandleNullPropagationOption(query),
					PageSize = actionDescriptor.PageSize(),
					SearchDerivedTypeWhenAutoExpand = true
				},
				AllowedQueryOptions.None);
			// Determine if this result should be a single entity
			
			if (ODataCountMediaTypeMapping.IsCountRequest(request))
			{
				long? count = request.ODataProperties().TotalCount;

				if (count.HasValue)
				{
					// Return the count value if it is a $count request.
					return count.Value;
				}
			}
			return query;
		}
开发者ID:joshcomley,项目名称:WebApi,代码行数:58,代码来源:EnableQueryAttribute.cs


示例10: GetBranchesCount

 public IHttpActionResult GetBranchesCount(ODataQueryOptions<Office> options)
 {
     IQueryable<Office> eligibleBranches = MonstersInc.Branches.AsQueryable();
     if (options.Filter != null)
     {
         eligibleBranches = options.Filter.ApplyTo(eligibleBranches, new ODataQuerySettings()).Cast<Office>();
     }
     return Ok(eligibleBranches.Count());
 }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:9,代码来源:MonstersIncController.cs


示例11: Get

        public Task<IHttpActionResult> Get([FromODataUri] Guid id, ODataQueryOptions<SaleHeader> options)
        {
            var sales = this.database.SaleHeaders.Where(s => s.Id == id);
            var expands = options.GetExpandPropertyNames();
            if (expands.Contains("SaleLineItems")) sales = sales.Include(s => s.Items);
            if (expands.Contains("CustomerContacts")) sales = sales.Include(s => s.CustomerContacts);

            return GetODataSingleAsync(sales, options);
        }
开发者ID:wei-zhou,项目名称:diamond,代码行数:9,代码来源:SalesController.cs


示例12: GetOrder

        // GET: odata/Orders(5)
        public IHttpActionResult GetOrder([FromODataUri] int key, ODataQueryOptions<Order> queryOptions)
        {
            if (key == 1)
            {
                return Ok(_someOrder);
            }

            return NotFound();
        }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:10,代码来源:OrdersController.cs


示例13: ValidateQuery

 public override void ValidateQuery(HttpRequestMessage request,
     ODataQueryOptions queryOptions)
 {
     if (queryOptions.OrderBy != null)
     {
         queryOptions.OrderBy.Validator = new MyOrderByValidator();
     }
     base.ValidateQuery(request, queryOptions);
 }
开发者ID:syfbme,项目名称:CDMISrestful,代码行数:9,代码来源:QueryValidation.cs


示例14: Validate

 /// <summary>
 /// Validates the specified query options.
 /// </summary>
 /// <param name="queryOptions">The query options.</param>
 /// <exception cref="ODataException">Thrown if the validation fails.</exception>
 internal static void Validate(ODataQueryOptions queryOptions)
 {
     if (queryOptions.Skip != null)
     {
         if (queryOptions.Skip.Value < 0)
         {
             throw new ODataException(Messages.SkipRawValueInvalid);
         }
     }
 }
开发者ID:TrevorPilley,项目名称:Net.Http.WebApi.OData,代码行数:15,代码来源:SkipQueryOptionValidator.cs


示例15: Ctor_SuccedsIfEntityTypesMatch

        public void Ctor_SuccedsIfEntityTypesMatch()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.EntitySet<Customer>("Customers");

            ODataQueryContext context = new ODataQueryContext(builder.GetEdmModel(), typeof(Customer));

            ODataQueryOptions<Customer> query = new ODataQueryOptions<Customer>(context, new HttpRequestMessage(HttpMethod.Get, "http://server/?$top=10"));
            Assert.Equal("10", query.Top.RawValue);
        }
开发者ID:ZhaoYngTest01,项目名称:WebApi,代码行数:10,代码来源:ODataQueryOptionsOfTEntityTest.cs


示例16: GetAllStats

        public IQueryable<SkaterStat> GetAllStats(ODataQueryOptions queryOptions)
        {
            //assume the client sends top and skip
            var filtered = _stats.Skip(queryOptions.Skip.Value);

            if (queryOptions.Top.Value > 0)
            {
                filtered = filtered.Take(queryOptions.Top.Value);
            }

            return filtered.AsQueryable();
        }
开发者ID:diouf,项目名称:apress-recipes-webapi,代码行数:12,代码来源:StatsController.cs


示例17: Put

 public async Task<IHttpActionResult> Put(int key, Customer customer, ODataQueryOptions<Customer> options)
 {
     if (!ModelState.IsValid)
     {
         return BadRequest(ModelState);
     }
     if (!(key == customer.Id))
     {
         return BadRequest("The customer Id must match the key in the URI");
     }
     if (options.IfMatch != null)
     {
         if (!_context.Customers.Where(c => c.Id == key).Any())
         {
             // The entity doesn't exist on the database and as the request contains an If-Match header we don't
             // insert the entity instead (No UPSERT behavior if the If-Match header is present).
             return NotFound();
         }
         else if (!((IQueryable<Customer>)options.IfMatch.ApplyTo(_context.Customers.Where(c => c.Id == key))).Any())
         {
             // The ETag of the entity doesn't match the value sent on the If-Match header, so the entity has
             // been modified by a third party between the entity retrieval and update..
             return StatusCode(HttpStatusCode.PreconditionFailed);
         }
         else
         {
             // The entity exists in the database and the ETag of the entity matches the value on the If-Match 
             // header, so we update the entity.
             _context.Entry(customer).State = EntityState.Modified;
             await _context.SaveChangesAsync();
             return Ok(customer);
         }
     }
     else
     {
         if (!_context.Customers.Where(c => c.Id == key).Any())
         {
             // The request didn't contain any If-Match header and the entity doesn't exist on the database, so
             // we create a new one. For more details see the section 11.4.4 of the OData v4.0 specification.
             _context.Customers.Add(customer);
             await _context.SaveChangesAsync();
             return base.Created(customer);
         }
         else
         {
             // the request didn't contain any If-Match header and the entity exists on the database, so we
             // update it's value.
             _context.Entry(customer).State = EntityState.Modified;
             await _context.SaveChangesAsync();
             return Ok(customer);
         }
     }
 }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:53,代码来源:CustomersController.cs


示例18: GetCustomers

        public IEnumerable<Customer> GetCustomers(ODataQueryOptions<Customer> queryOptions)
        {
            // validate the query.
            queryOptions.Validate(_validationSettings);

            // Apply the query.
            IQuery query = queryOptions.ApplyTo(_db);

            Console.WriteLine("Executing HQL:\t" + query);
            Console.WriteLine();

            return query.List<Customer>();
        }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:13,代码来源:CustomersController.cs


示例19: GetImages

        // GET: odata/Images
        public PageResult<Image> GetImages(ODataQueryOptions<Image> options)
        {
            ODataQuerySettings settings = new ODataQuerySettings()
            {
                PageSize = CollectionOfWorkers.SizeOfPage
            };

            IQueryable results = options.ApplyTo(db.Images.AsQueryable(), settings);

            return new PageResult<Image>(
                results as IEnumerable<Image>,
                null,
                db.Images.Count());
        }
开发者ID:XDIM2006,项目名称:OfiiceWithMSMQ-and-WinService,代码行数:15,代码来源:ImagesController.cs


示例20: GetOrder

        // GET: odata/Orders(5)
        public IHttpActionResult GetOrder([FromODataUri] int key, ODataQueryOptions<Order> queryOptions)
        {
            // validate the query.
            try
            {
                queryOptions.Validate(_validationSettings);
            }
            catch (ODataException ex)
            {
                return BadRequest(ex.Message);
            }

            // return Ok<Order>(order);
            return StatusCode(HttpStatusCode.NotImplemented);
        }
开发者ID:nickgoodrow,项目名称:ODataSamples,代码行数:16,代码来源:OrdersController.cs



注:本文中的ODataQueryOptions类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# ODataValidationSettings类代码示例发布时间:2022-05-24
下一篇:
C# ODataQueryContext类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap