本文转自:http://www.odata.org/blog/how-to-use-web-api-odata-to-build-an-odata-v4-service-without-entity-framework/

Mar 12, 2015 • Qian Li

There are quite a lot of tutorials showing how to create OData services using Web API OData, but these requires Entity Framework and a database server behind. If you want a quick try or you have your own way of implementing data sources, these tutorials may not be the best fit. In this article, we will show how to build an OData service using in-memory data as data source and with basic function.

Create the solution

Create a new solution following File -> New -> Project -> Web, then choose ASP.NET Web Application. Name it with Demo. Then in the upcoming dialogue box, choose Empty and check Web API, click OK.

Install NuGet packages

Run the following command in the Package Manager Console.

PM> Install-Package Microsoft.AspNet.OData

Add Models

In this getting-started example, we just add two model class Person.cs and Trip.cs under folder Models. Person can navigate to Trips.

using System;
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
public class Person
{
[Key]
public String ID { get; set; }
[Required]
public String Name { get; set; }
public String Description { get; set; }
public List<Trip> Trips { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Demo.Models
{
public class Trip
{
[Key]
public String ID { get; set; }
[Required]
public String Name { get; set; }
}
}

The attributes [Key] and [Required] are all from System.ComponentModel.DataAnnotations meaning the property is key and required seperately.

In-Memory data source

This tutorial uses in-memory data source, which is more flexible. Below are only one way to implement, you can definitely have your only way.

Add a folder DataSource and add a class file DemoDataSources.cs with the code below.

using Demo.Models;
using System.Collections.Generic;
namespace Demo.DataSource
{
public class DemoDataSources
{
private static DemoDataSources instance = null;
public static DemoDataSources Instance
{
get
{
if (instance == null)
{
instance = new DemoDataSources();
}
return instance;
}
}
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()
{
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"
},
new Trip()
{
ID = "3",
Name = "Trip 3"
}
});
this.People.AddRange(new List<Person>
{
new Person()
{
ID = "001",
Name = "Angel",
Trips = new List<Trip>{Trips[0], Trips[1]}
},
new Person()
{
ID = "002",
Name = "Clyde",
Description = "Contrary to popular belief, Lorem Ipsum is not simply random text.",
Trips = new List<Trip>{Trips[2], Trips[3]}
},
new Person()
{
ID = "003",
Name = "Elaine",
Description = "It has roots in a piece of classical Latin literature from 45 BC, making Lorems over 2000 years old."
}
});
}
}
}

Add Controllers

Since there are two entity set, we will add two controller class under the folder Controllers

First is controller for People

using Demo.DataSource;
using System.Linq;
using System.Web.Http;
using System.Web.OData;
namespace Demo.Controllers
{
[EnableQuery]
public class PeopleController : ODataController
{
public IHttpActionResult Get()
{
return Ok(DemoDataSources.Instance.People.AsQueryable());
}
}
}

Then is the controller for Trips

using Demo.DataSource;
using System.Linq;
using System.Web.Http;
using System.Web.OData;
namespace Demo.Controllers
{
[EnableQuery]
public class TripsController : ODataController
{
public IHttpActionResult Get()
{
return Ok(DemoDataSources.Instance.Trips.AsQueryable());
}
}
}

In this very simple implementation, only simple Get with query options are allowed. If you want to enable more capabilities in your controller, the code is quite similar with what's done with EF as data source. Please refer to ASP.NET Web API OData V4 Samples and Create an OData v4 Endpoint Using ASP.NET Web API 2.2.

Configure the Endpoint

The last step is to modify the WebApiConfig.cs file under App_Start.

using Demo.Models;
using Microsoft.OData.Edm;
using System.Web.Http;
using System.Web.OData.Batch;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
namespace Demo
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
config.EnsureInitialized();
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "Demos";
builder.ContainerName = "DefaultContainer";
builder.EntitySet<Person>("People");
builder.EntitySet<Trip>("Trips");
var edmModel = builder.GetEdmModel();
return edmModel;
}
}
}

Try with it

It's done to create a very basic OData endpoint with in-memory data source using Web API OData. You can try it out now! All samples below are all GET method.

Service document

http://localhost:[portNumber]/

Service metadata

http://localhost:[portNumber]/$metadata

Get People

http://localhost:[portNumber]/People

Queries

http://localhost:[portNumber]/People?$filter=contains(Description,'Lorem')

http://localhost:[portNumber]/People?$select=Name

http://localhost:[portNumber]/People?$expand=Trips

[转]How to Use Web API OData to Build an OData V4 Service without Entity Framework的更多相关文章

  1. 【ASP.NET Web API教程】2.3 与实体框架一起使用Web API

    原文:[ASP.NET Web API教程]2.3 与实体框架一起使用Web API 2.3 Using Web API with Entity Framework 2.3 与实体框架一起使用Web ...

  2. asp.net web api 2.2 基础框架(带例子)

    链接:https://github.com/solenovex/asp.net-web-api-2.2-starter-template 简介 这个是我自己编写的asp.net web api 2.2 ...

  3. [转]Creating an OData v3 Endpoint with Web API 2

    本文转自:https://docs.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata- ...

  4. [转]Work With Odata in Web API: Create Your First Odata Service

    本文转自:http://www.c-sharpcorner.com/UploadFile/dacca2/work-with-odata-in-web-api-create-your-first-oda ...

  5. Web Api 简介

    ASP.NET Web API 简介  ASP.NET MVC 4 包含了 ASP.NET Web API, 这是一个创建可以连接包括浏览器.移动设备等多种客户端的 Http 服务的新框架, ASP. ...

  6. ASP.NET Web API 简介

    ASP.NET MVC 4 包含了 ASP.NET Web API, 这是一个创建可以连接包括浏览器.移动设备等多种客户端的 Http 服务的新框架, ASP.NET Web API 也是构建 RES ...

  7. [水煮 ASP.NET Web API 2 方法论] 目 录

    一.ASP.NET 中的 Web API [水煮 ASP.NET Web API2 方法论](1-1)在MVC 应用程序中添加 ASP.NET Web API 与 ASP.NET MVC 在同一个进程 ...

  8. ASP.NET Web API 特性

    ASP.NET MVC 4 包含了 ASP.NET Web API, 这是一个创建可以连接包括浏览器.移动设备等多种客户端的 Http 服务的新框架, ASP.NET Web API 也是构建 RES ...

  9. Asp.net web api 知多少

    本系列主要翻译自<ASP.NET MVC Interview Questions and Answers >- By Shailendra Chauhan,想看英文原版的可访问http:/ ...

随机推荐

  1. js webstrom中svn的配置及使用

    js  webstorm中svn的配置及使用 一.webstorm配置svn: 1.在webstorm工具中找到file(文件)-setting(设置)菜单按钮: 2.在左边菜单中找到plus(插件) ...

  2. MongoDB集群搭建-分片

    MongoDB集群搭建-分片 一.场景: 1,机器的磁盘不够用了.使用分片解决磁盘空间的问题. 2,单个mongod已经不能满足写数据的性能要求.通过分片让写压力分散到各个分片上面,使用分片服务器自身 ...

  3. hdu 1542/1255 Atlantis/覆盖的面积

    1542 1255 两道扫描线+线段树的入门题. 基本没有什么区别,前者是模板,后者因为是求覆盖次数至少在两次以上的,这个同样是具有并集性质的,所以把cover的判断条件更改一下就可以了qwq. hd ...

  4. django中models联合唯一unique_together

    例: 文章点赞 class ArticleUpDown(models.Model): """ 点赞表 """ nid = models.Au ...

  5. [Maven实战-许晓斌]-[第三章] Mave使用入门

    <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://mave ...

  6. bzoj 4283 魔法少女伊莉雅

    题目大意 给定一个 $n$ 个点 $m$ 条边的带正权无向图.要求找一条路径满足: 它是一条简单路径 它是一条严格次短路 对于任何一条可能存在于最短路上的边,不能包含它的反向边. 不存在这条路径输出 ...

  7. Linux 下四条高大命令(计划360检测脚本)

    查看进程,按内存从大到小 ps -e -o "%C : %p : %z : %a"|sort -k5 -nr 查看进程,按CPU利用率从大到小排序 ps -e -o "% ...

  8. react-router的简单使用

    React Router是一个基于React之上的强大路由库,可以让你向应用中快速的添加视图和数据流,同时保持页面与URL间的同步. 1.安装: npm install --save react-ro ...

  9. python全栈开发_day6_元组,字典,集合

    一:元组    1)定义    元组:有序,可以按索引取值,不可变,但是可以修改元组里面可变数据的数据内容. res = (1,2,3,4,3,2,1) 2)内置方法和使用 res.count(1) ...

  10. SQL多字段排序

    emm 其实也没什么 就是写sql查询的时候 要对多个字段排序比如  查询原本的数据是 年份 科目 批次 2014 理科 本二2015 理科 本二 2015 理科 本一2016 理科 本二 2016 ...