一、OData介绍

开放数据协议(Open Data Protocol,缩写OData)是一种描述如何创建和访问Restful服务的OASIS标准。

二、OData 在asp.net mvc中的用法

  1、在vs中新建webApi项目

2、添加测试类型

 public class Product
{
public int Id { get; set; } public string ProductName
{
get; set;
}
}

3、开启EF自动迁移,添加EF上下文,

namespace ODataTest.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
using ODataTest.Models; internal sealed class Configuration : DbMigrationsConfiguration<ODataTest.Models.EFContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
} protected override void Seed(ODataTest.Models.EFContext context)
{
// This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. }
}
}
 public class EFContext : DbContext
{ static EFContext()
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<EFContext, Configuration>());
}
public EFContext() : base("DefaultConnection")
{
} public DbSet<Product> Products { get; set; }
}

4.在数据库添加一些测试数据

Id ProductName
21 产品1
22 产品2
23 产品3
24 产品4

5、在Controllers文件夹添加OData控制器

6、vs将自动生成基本的CURD,

将GetProducts方法的EnableQuery特性的AllowedQueryOptions属性设置为:允许所有查询AllowedQueryOptions.All

    public class ProductsController : ODataController
{
private EFContext db = new EFContext(); // GET: odata/Products
[EnableQuery(AllowedQueryOptions = AllowedQueryOptions.All)]
public IQueryable<Product> GetProducts()
{
return db.Products;
} // GET: odata/Products(5)
[EnableQuery]
public SingleResult<Product> GetProduct([FromODataUri] int key)
{
return SingleResult.Create(db.Products.Where(product => product.Id == key));
} // PUT: odata/Products(5)
public IHttpActionResult Put([FromODataUri] int key, Delta<Product> patch)
{
Validate(patch.GetEntity()); if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} patch.Put(product); try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
} return Updated(product);
} // POST: odata/Products
public IHttpActionResult Post(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} db.Products.Add(product);
db.SaveChanges(); return Created(product);
} // PATCH: odata/Products(5)
[AcceptVerbs("PATCH", "MERGE")]
public IHttpActionResult Patch([FromODataUri] int key, Delta<Product> patch)
{
Validate(patch.GetEntity()); if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} patch.Patch(product); try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(key))
{
return NotFound();
}
else
{
throw;
}
} return Updated(product);
} // DELETE: odata/Products(5)
public IHttpActionResult Delete([FromODataUri] int key)
{
Product product = db.Products.Find(key);
if (product == null)
{
return NotFound();
} db.Products.Remove(product);
db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent);
} protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
} private bool ProductExists(int key)
{
return db.Products.Count(e => e.Id == key) > ;
}
}

7、在WebApiConfig类的Register方法里面注册OData路由

using System.Web.Http;
using System.Web.Http.OData.Builder;
using System.Web.Http.OData.Extensions;
using ODataTest.Models; ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

8、运行网站就可以在浏览器就行OData的API测试

  常用查询:

  查询所有:http://localhost:64643/odata/Products

  根据主键进行查询:http://localhost:64643/odata/Products(22)  【22为主键值】

  相等查询:http://localhost:64643/odata/Products?$filter=ProductName eq '产品1'

只查询部分字段:http://localhost:64643/odata/Products?$select=Id

  模糊查询(这个找了老半天):http://localhost:64643/odata/Products?$filter=substringof('品1',ProductName) eq true  

  还有更多的查询,参考,http://www.odata.org/documentation/odata-version-3-0/url-conventions/ ,在mvc中使用EF和OData基本能够满足所有的前端查询,有利于快速开发API查询接口

webAPi OData的使用的更多相关文章

  1. OData – the best way to REST–实例讲解ASP.NET WebAPI OData (V4) Service & Client

    一.概念介绍 1.1,什么是OData? 还是看OData官网的简单说明: An open protocol to allow the creation and consumption of quer ...

  2. AspNet WebApi OData 学习

    OData介绍:是一个查询和更新数据的Web协议.OData应用了web技术如HTTP.Atom发布协议(AtomPub)和JSON等来提供对不同应用程序,服务 和存储的信息访问.除了提供一些基本的操 ...

  3. AspNet.WebAPI.OData.ODataPQ

    AspNet.WebAPI.OData.ODataPQ实现WebAPI的分页查询服务 AspNet.WebAPI.OData.ODataPQ实现WebAPI的分页查询服务-(个人拙笔) AspNet. ...

  4. AspNet.WebAPI.OData.ODataPQ实现WebAPI的分页查询服务-(个人拙笔)

    AspNet.WebAPI.OData.ODataPQ 这是针对 Asp.net WebAPI OData 协议下,查询分页.或者是说 本人在使用Asp.Net webAPI 做服务接口时写的一个分页 ...

  5. 主攻ASP.NET MVC4.0之重生:Asp.Net MVC WebApi OData

    1.新建MVC项目,安装OData Install-Package Microsoft.AspNet.WebApi.OData -Version 4.0.0 2.新建WebAPI Controller ...

  6. AspNet.WebAPI.OData.ODataPQ实现WebAPI的分页查询服务-(个人拙笔)(转)

    出处:http://www.bubuko.com/infodetail-827612.html AspNet.WebAPI.OData.ODataPQ 这是针对 Asp.net WebAPI ODat ...

  7. [转]Composite Keys With WebApi OData

    本文转自:http://chris.eldredge.io/blog/2014/04/24/Composite-Keys/ In our basic configuration we told the ...

  8. [转]OData – the best way to REST–实例讲解ASP.NET WebAPI OData (V4) Service & Client

    本文转自:http://www.cnblogs.com/bluedoctor/p/4384659.html 一.概念介绍 1.1,什么是OData? 还是看OData官网的简单说明: An open ...

  9. 基于Angular+WebAPI+OData的增删改查

    对于在ASP.NET WebAPI中怎么使用OData,已经在我前面的日志中的说明, 在ASP.NET Web API中使用OData 在这个示例中.我新建了一个Order的实体,在前端使用Angul ...

随机推荐

  1. 高手速成android开源项目【View篇】

    主要介绍那些不错个性化的View,包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.ProgressBar及其他如Dialo ...

  2. Ajax经典交互讲解

    资料: XMLHttpRequest 对象 XMLHttpRequest 对象提供了对 HTTP 协议的完全的访问,包括做出 POST 和 HEAD 请求以及普通的 GET 请求的能力.XMLHttp ...

  3. 实验吧 貌似有点难 伪造ip

    解题链接: http://ctf5.shiyanbar.com/phpaudit/ 解答: 点击View the source code —>代码显示IP为1.1.1.1即可得到KEY—> ...

  4. Docker安装(Debian8)-构建简单的SpringBoot应用

    安装docker 1. 建立仓库 移除已安装的docker(docker以前被称为docker或者docker-enginer现在称为docker-ce) apt-get remove docker ...

  5. C语言指针基本操作

    C语言指针基本操作 指针  指针介绍 如果说C语言最有魅力的地方在哪,那么毋庸置疑,非指针莫属了. 众所周知,C语言中每个变量都有一个内存地址,可以通过&进行访问.指针是一个变量,它的值是一个 ...

  6. python argparse(参数解析模块)

    这是一个参数解析,可以用它快捷的为你的程序生成参数相关功能 import argparse(导入程序参数模块) # 创建argparse对象,并将产品简要说明加入show = '程序说明' ===&g ...

  7. 自动化运维(1)之二进制部署MySQL5.7

    二进制部署MySQL5.7 这个文档用于基础解释,后面通过ansible的自动化对MySQL单实例进行安装部署. 1.解压文件 # tar zxvf mysql-5.7.22-linux-glibc2 ...

  8. C# 基础运算符及运算

    本节主要讲述运算符的分类及其实际运用 运算符 分类 符号 解释 优先级 算数 ++  -- 加加(加1)  减减(减1) 由高到低,即执行顺序由上到下(圆括号的优先级最高) *  /  % 乘  除  ...

  9. elasticsearch6.7 05. Document APIs(5)Delete By Query API

    4.Delete By Query API _delete_by_query API可以删除某个匹配条件的文档: POST twitter/_delete_by_query { "query ...

  10. GBK与UTF-8的区别

    GBK的文字编码是双字节来表示的,即不论中.英文字符均使用双字节来表示,只不过为区分中文,将其最高位都定成1. 至于UTF-8编码则是用以解决国际上字符的一种多字节编码,它对英文使用8位(即一个字节) ...