本文转自: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. 日笔记--C# 从数据库取表格到DataGridView---json传输

    只作为个人学习笔记. class OpData { // 创建一个和客户端通信的套接字 Socket socketwatch = null; //连接Access字符串 string strCon; ...

  2. 虚拟化 - Hyper-V

    不能和VMware.VirtualBox同时使用 网络 交换机其实就是指网卡,只不过是虚拟的 内部交换机 外部交换机

  3. ClassNotFoundException和 NoClassDefFoundError的区别

    ##### 1. 类型 ClassNotFoundException继承自Exception,属于java异常类.NoClassDefFoundError继承自Error,在java中Error一般属 ...

  4. mxonline实战8,机构列表分页功能,以及按条件筛选功能

    对应github地址:列表分页和按条件筛选     一. 列表分页   1. pip install django-pure-pagination   2. settings.py中 install ...

  5. nginx配置文件中,location字段里面的root字段和别名alias

    1. location里面的root例子 server{ listen ; server_name www.wzw.com; location /www { root /data/; //设置虚拟主机 ...

  6. ansible api2.0 多进程执行不同的playbook

    自动化运维工具:ansible 多进程调用ansible api的应用场景:   应用系统检查 一个应用系统可能具有20—50台服务器的集群,初步的系统层面检查可以用一个统一的playbook来检查, ...

  7. leetcode-219-Contains Duplicate II(使用set来判断长度为k+1的闭区间中有没有重复元素)

    题目描述: Given an array of integers and an integer k, find out whether there are two distinct indices i ...

  8. 语音转文字小工具开发Python

    # -*- coding: utf- -*- import requests import re import os import time from aip import AipSpeech fro ...

  9. DGIS之遥感影像数据获取

    1.概要 在GIS圈的同行或多或少接触过遥感,记得在大学老师就说过"数据是GIS的核心".本文介绍在国内下载遥感影像的方法. 地理空间数据云,这个是中科院计算机网络中心建设的一个免 ...

  10. JavaSwing程序设计(目录)

    一.JavaSwing 概述 JavaSwing 图形界面概述 二.JavaSwing 基本组件 JLabel(标签) JButton(按钮) JTextField(文本框) JPasswordFie ...