本文转自:http://chris.eldredge.io/blog/2014/04/24/Composite-Keys/

In our basic configuration we told the model builder that our entity has a composite key comprised of an ID and a version:

1
2
3
4
5
6
7
8
9
10
public void MapDataServiceRoutes(HttpConfiguration config)
{
var builder = new ODataConventionModelBuilder(); var entity = builder.EntitySet<ODataPackage>("Packages");
entity.EntityType.HasKey(pkg => pkg.Id);
entity.EntityType.HasKey(pkg => pkg.Version); // snip
}

This is enough for our OData feed to render edit and self links for each individual entity in a form like:

http://localhost/odata/Packages(Id='Sample',Version='1.0.0')

But if we navigate to this URL, instead of getting just this one entity by key, we get back the entire entity set.

To get the correct behavior, first we need an override on our PackagesODataController that gets an individual entity instance by key:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class PackagesODataController : ODataController
{
public IMirroringPackageRepository Repository { get; set; } public IQueryable<ODataPackage> Get()
{
return Repository.GetPackages().Select(p => p.ToODataPackage()).AsQueryable();
} public IHttpActionResult Get(
[FromODataUri] string id,
[FromODataUri] string version)
{
var package = Repository.FindPackage(id, version); return package == null
? (IHttpActionResult)NotFound()
: Ok(package.ToODataPackage());
}
}

However, out of the box WebApi OData doesn’t know how to bind composite key parameters to an action such as this, since the key is comprised of multiple values.

We can fix this by creating a new routing convention that binds the stuff inside the parenthesis to our route data map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class CompositeKeyRoutingConvention : IODataRoutingConvention
{
private readonly EntityRoutingConvention entityRoutingConvention =
new EntityRoutingConvention(); public virtual string SelectController(
ODataPath odataPath,
HttpRequestMessage request)
{
return entityRoutingConvention
.SelectController(odataPath, request);
} public virtual string SelectAction(
ODataPath odataPath,
HttpControllerContext controllerContext,
ILookup<string, HttpActionDescriptor> actionMap)
{
var action = entityRoutingConvention
.SelectAction(odataPath, controllerContext, actionMap); if (action == null)
{
return null;
} var routeValues = controllerContext.RouteData.Values; object value;
if (!routeValues.TryGetValue(ODataRouteConstants.Key,
out value))
{
return action;
} var compoundKeyPairs = ((string)value).Split(','); if (!compoundKeyPairs.Any())
{
return null;
} var keyValues = compoundKeyPairs
.Select(kv => kv.Split('='))
.Select(kv =>
new KeyValuePair<string, object>(kv[0], kv[1])); routeValues.AddRange(keyValues); return action;
}
}

This class decorates a standard EntityRoutingConvention and splits the raw key portion of the URI into key/value pairs and adds them all to the routeValues dictionary.

Once this is done the standard action resolution kicks in and finds the correct action overload to invoke.

This routing convention was adapted from the WebApi ODataCompositeKeySampleproject.

Here we see another difference between WebApi OData and WCF Data Services. In WCF Data Services, the framework handles generating a query that selects a single instance from an IQueryable. This limits our ability to customize how finding an instance by key is done. In WebApi OData, we have to explicitly define an overload that gets an entity instance by key, giving us more control over how the query is executed.

This distinction might not matter for most projects, but in the case of NuGet.Lucene.Web, it enables a mirror-on-demand capability where a local feed can fetch a package from another server on the fly, add it to the local repository, then send it back to the client as if it was always there in the first place.

To customize this in WCF Data Services required significant back flips.

Series Index

  1. Introduction
  2. Basic WebApi OData
  3. Composite Keys
  4. Default Streams

[转]Composite Keys With WebApi OData的更多相关文章

  1. [转]Web API OData V4 Keys, Composite Keys and Functions Part 11

    本文转自:https://damienbod.com/2014/09/12/web-api-odata-v4-keys-composite-keys-and-functions-part-11/ We ...

  2. 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 ...

  3. AspNet WebApi OData 学习

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

  4. AspNet.WebAPI.OData.ODataPQ

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

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

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

  6. 主攻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 ...

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

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

  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. webAPi OData的使用

    一.OData介绍 开放数据协议(Open Data Protocol,缩写OData)是一种描述如何创建和访问Restful服务的OASIS标准. 二.OData 在asp.net mvc中的用法 ...

随机推荐

  1. pageadmin网站制作 怎么验证sql用户名和密码的正确性

    使用pageadmin建站系统的时候,不懂可以参考官网教程. 1.打开SQL Server Management Studio会弹出如下界面. 第一个箭头指向的就是服务器名称,如果用ip无法连接sql ...

  2. Android 文件读写高级

    往设备里写文件有几种选择,写在内存中,或SD卡中. 往内存里写好处是,可以写在 data/data/包名 文件夹里,而此文件是不可访问的(除非 root).这样可以增加文件的安全性,避免被误删.缺点也 ...

  3. python单引号和双引号的区别

    今天在网上爬虫的时候,很奇怪的发现python的字符串既可以用双引号又可以用单引号,于是就上网百度了一下原因. 原来由于字符串中有可能既有双引号又有单引号,例如: 字符串:demo'1'. 这时候就可 ...

  4. java—过虑器基础(47)

    在web项目中就只有三大组件: Filter过虑器 监听器. Servlet 在web中过虑器就是一个类javax.servlet.Filter. 过虑器是用于在执行时,过虑用户的请求(request ...

  5. Microsoft Visual C++ 14.0 is required

    building 'twisted.test.raiser' extensionerror: Microsoft Visual C++ 14.0 is required. Get it with &q ...

  6. Gym-101873D-Pants On Fire(闭包)

    原题链接:2017-2018 ACM-ICPC German Collegiate Programming Contest (GCPC 2017) Pants On Fire Donald and M ...

  7. 解决无法运行Terminator出现以下问题: File "/usr/bin/terminator"...SyntaxError: invalid syntax

    在安装或者启动Terminator时可能出现这个问题: lin@Dev:~$ terminator File "/usr/bin/terminator", line 123 exc ...

  8. javascript如何阻止事件冒泡和默认行为

    阻止冒泡:    冒泡简单的举例来说,儿子知道了一个秘密消息,它告诉了爸爸,爸爸知道了又告诉了爷爷,一级级传递从而以引起事件的混乱,而阻止冒泡就是不让儿子告诉爸爸,爸爸自然不会告诉爷爷.下面的demo ...

  9. orcal创建序列

    CREATE SEQUENCE flowjobseq --序列名INCREMENT BY 1 -- 每次加几个 START WITH 2000 -- 从1开始计数 NOMAXVALUE -- 不设置最 ...

  10. Hexo博客系列(二)-在多台机器上利用Hexo发布博客

    [原文链接]:https://www.tecchen.xyz/blog-hexo-env-02.html 我的个人博客:https://www.tecchen.xyz,博文同步发布到博客园. 由于精力 ...