多个OData实体GET方法

时间:2014-08-06 13:46:13

标签: entity-framework get odata

我使用OData和实体框架来创建一个简单的Web服务。一切正常。我只需要知道如何添加额外的GET命令,例如" GetByCategory"或" GetByDate"。这些将使用不同的SQL视图来返回复杂的过滤结果。

** WebApiConfig.cs *

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using NRHSData.Models;

namespace NRHSData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
            config.AddODataQueryFilter();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            builder.Namespace = "NRHSData";
            builder.EntitySet<employee>("employees");
            builder.EntitySet<vw_employee_listing>("vw_employee_listings");
            builder.EntitySet<physician>("physicians");
            builder.EntitySet<vw_physician_listing>("vw_physician_listings");
            builder.EntitySet<employeedepartment>("employeedepartments");
            builder.EntitySet<vw_employeedepartment_listing>("vw_employeedepartment_listings");
            builder.EntitySet<news>("news");
            builder.EntitySet<vw_news_listing>("vw_news_listings");
            builder.EntitySet<vw_news_current>("vw_news_current");

            config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
        }
    }
}

** newsController.cs *

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using System.Web.Http.OData;
using System.Web.Http.OData.Routing;
using NRHSData.Models;

namespace NRHSData.Controllers
{
    [Authorize]
    public class newsController : ODataController
    {
        private ENTDATAEntities db = new ENTDATAEntities();

        // GET: odata/news
        [EnableQuery]
        public IQueryable<vw_news_listing> Getnews()
        {
            return db.vw_news_listings;
        }

        // GET: odata/news(5)
        [EnableQuery]
        public SingleResult<vw_news_listing> Getnews([FromODataUri] int key)
        {
            return SingleResult.Create(db.vw_news_listings.Where(news => news.newsid == key));
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool newsExists(int key)
        {
            return db.news.Count(e => e.newsid == key) > 0;
        }

        // PUT: odata/news(5)
        public async Task<IHttpActionResult> Put([FromODataUri] int key, Delta<news> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            news news = await db.news.FindAsync(key);
            if (news == null)
            {
                return NotFound();
            }

            patch.Put(news);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!newsExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(news);
        }

        // POST: odata/news
        public async Task<IHttpActionResult> Post(news news)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.news.Add(news);
            await db.SaveChangesAsync();

            return Created(news);
        }

        // PATCH: odata/news(5)
        [AcceptVerbs("PATCH", "MERGE")]
        public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<news> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            news news = await db.news.FindAsync(key);
            if (news == null)
            {
                return NotFound();
            }

            patch.Patch(news);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!newsExists(key))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return Updated(news);
        }

        // DELETE: odata/news(5)
        public async Task<IHttpActionResult> Delete([FromODataUri] int key)
        {
            news news = await db.news.FindAsync(key);
            if (news == null)
            {
                return NotFound();
            }

            db.news.Remove(news);
            await db.SaveChangesAsync();

            return StatusCode(HttpStatusCode.NoContent);
        }

    }
}

1 个答案:

答案 0 :(得分:0)

我假设您正在尝试解决此类请求:

~/News/GetByDate()

有两个选项:

  1. 使用OData操作。添加名为GetByDate的操作,并通过&#39; POST~ / News / GetByDate()&#39;发出请求。但它不符合协议。行动应该有一些副作用。所以第二个选择来了。

  2. 使用OData函数,它不能有副作用。要实现此功能,您需要升级到新位:System.Web.OData.dll。这是一个关于函数的示例:https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ODataFunctionSample/