OData v4 - Web API 轻量级应用(无Entity Framwork)

本文讲述的是简单的Web API OData使用。一般的,OData应用需要使用到Entity Framwork和database server来实现datasource,在本文中,为了快速的实现OData service,本文使用了in-memory data作为datasource。以下是创建过程。

solution 全览


创建solution

File->new>Project>Web->Web Application  重命名

安装NuGet包

  • 方法一:运行tools->NuGet package manager->Package manager console
PM> Install-Package Microsoft.AspNet.OData
  • 方法二:solution下面的References右键Manage NuGet packages ,online查询并安装odata应用包

创建Models

在Models文件夹下创建两个model class, 分别是Person.cs 和Trip.cs,其中Person model能够前往(navigate to)Trips.

public class Person
    {
        [Key] //from System.ComponentModel.DataAnnotations meaning the property is key
        public String ID { get; set; }
        [Required]  // from System.ComponentModel.DataAnnotations meaning the property is required seperately.
        public String Name { get; set; }
        public String Description { get; set; }
        public List<Trip> Trips { get; set; }
    }
public class Trip
    {
        [Key]
        public String ID { get; set; }
        [Required]
        public String Name { get; set; }
    }

In-Memory dataSource实现

添加DataSource file->添加DemoDataSources.cs

 public class DemoDataSources
    {
        private static DemoDataSources instance = null;
        public static DemoDataSources Instance
        {
            get { return instance ?? (instance = new DemoDataSources()); }
        }
        public List<Person> People { get; set; }
        public List<Trip> Trips { get; set; }
        private DemoDataSources()
        {
            this.Reset();
            this.Initialize();
        }
        public void Reset()
        {
            this.People = new List<Person>();
            this.Trips = new List<Trip>();
        }
        public void Initialize()
        {  //initialize trips
            this.Trips.AddRange(new List<Trip>(){
                new Trip(){
                    ID = "0",
                    Name = "Trip 0"
                },
                new Trip(){
                    ID = "1",
                    Name = "Trip 1"
                },
                new Trip(){
                    ID = "2",
                    Name = "Trip 2"
                }
            });
            //initialize people
            this.People.AddRange(new List<Person>(){
                new Person(){
                    ID = "001",
                    Name = "Demi",
                    Trips = new List<Trip>{Trips[0], Trips[1]}
                },
                new Person(){
                    ID = "002",
                    Name = "Claire",
                    Description = "This is a beautiful girl!",
                    Trips = new List<Trip>{Trips[1], Trips[2],Trips[0]}
                }
            });
        }
    }


添加controllers

前面model中有两个entity set(实体集),在这里我们就需要对应创建两个controller,分别是PeopleController.cs和TripsController.cs。本文中只是给出了简单的Get查询方法,也可以增加其他的Odata操作方法,并且实现方法与使用EF实现的DataSource中类似。

[EnableQuery]
    public class PeopleController : ODataController
    {
        public IHttpActionResult Get()
        {
            return Ok(DemoDataSources.Instance.People.AsQueryable());
        }
    }
[EnableQuery]
    public class TripsController : ODataController
    {
        public IHttpActionResult Get()
        {
            return Ok(DemoDataSources.Instance.Trips.AsQueryable());
        }
    }

配置endpoint

public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            //config.MapHttpAttributeRoutes();

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

            config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
            config.EnsureInitialized();

        }

        private static IEdmModel GetEdmModel()
        {
            var builder = new ODataConventionModelBuilder {Namespace = "Demos", ContainerName = "DefaultContainer"};
            builder.EntitySet<Person>("People");
            builder.EntitySet<Trip>("Trips");
            var edmModel = builder.GetEdmModel();
            return edmModel;
        }

运行效果

所有的GET方法

http://localhost:26388 - service document

http://localhost:26388/$metadata - service metadata

http://localhost:26388/People - get all

http://localhost:26388/People?$filter=contains(Description,'girl') - filter

http://localhost:26388/People?$select=Name - select

http://localhost:26388/People?$expand=Trips - expand







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值