0

0

[转]Support Composite Key in ASP.NET Web API OData

PHP中文网

PHP中文网

发布时间:2017-06-17 16:33:57

|

2036人浏览过

|

来源于php中文网

原创

本文转自:

he default EntitySetController doesn't support composite keys. So if you have composite key models, you need some additional work. Here is an example about how to do that.

The model is simple:

public class Person
{
    [Key]
    public string FirstName { get; set; }
    [Key]
    public string LastName { get; set; }

    public int Age { get; set; }
}

The odata url for this model will look like:

GET http://localhost:33051/People(FirstName='Kate',LastName='Jones') HTTP/1.1

And we want to have strong typed parameters in web api actions to this URL.

    public Person Get([FromODataUri] string firstName, [FromODataUri] string lastName)

Note that the FromODataUri model binder attribute is used to parse from odata uri representation to clr type. In odata, string value is "'xxx'" and we want it to be "xxx".

In order to make the route to work, you can add a custom routing convention to parse the key path. Here is a sample implementation:

public class CompositeKeyRoutingConvention : EntityRoutingConvention
{
    public override string SelectAction(System.Web.Http.OData.Routing.ODataPath odataPath, System.Web.Http.Controllers.HttpControllerContext controllerContext, ILookup actionMap)
    {
        var action = base.SelectAction(odataPath, controllerContext, actionMap);
        if (action != null)
        {
            var routeValues = controllerContext.RouteData.Values;
            if (routeValues.ContainsKey(ODataRouteConstants.Key))
            {
                var keyRaw = routeValues[ODataRouteConstants.Key] as string;
                IEnumerable compoundKeyPairs = keyRaw.Split(',');
                if (compoundKeyPairs == null || compoundKeyPairs.Count() == 0)
                {
                    return action;
                }

                foreach (var compoundKeyPair in compoundKeyPairs)
                {
                    string[] pair = compoundKeyPair.Split('=');
                    if (pair == null || pair.Length != 2)
                    {
                        continue;
                    }
                    var keyName = pair[0].Trim();
                    var keyValue = pair[1].Trim();

                    routeValues.Add(keyName, keyValue);
                }
            }
        }

        return action;
    }
}

The convention is inherited from EntityRoutingConvention, which is the default convetion to handle entity key. By calling base.SelectAction, it will add the full key path into routeValues. The new convention will check if it contains "," and seperate it into multiple keys and set each of them into routeValues. So when web api select actions, it will use those values to determine which action to choose. If there is no "," found, it behaves same as base convetion.

Flowith
Flowith

一款GPT4驱动的节点式 AI 创作工具

下载

To register the convetion, you need to set it when mapping odata route:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableQuerySupport();

        var mb = new ODataConventionModelBuilder(config);
        mb.EntitySet("People");

        var conventions = ODataRoutingConventions.CreateDefault();
        conventions.Insert(0, new CompositeKeyRoutingConvention());

        config.Routes.MapODataRoute(
            routeName: "OData", 
            routePrefix: null, 
            model: mb.GetEdmModel(), 
            pathHandler: new DefaultODataPathHandler(), 
            routingConventions: conventions);
    }
}

Register the route at the postion 0 is to make it be executed before other default routing convetions. So the default EntityRoutingConvetion won't be executed before it. After that, you should be able to get routing work.

Then, how to build url for composite keys? 
You don't need to do that for odata links include edit link and self link when using ODataConventionModelBuilder. It will automatically identify composite keys and build the uri for you.

However, you need to build the link for location header. Here is a sample code from PeopleController.cs to handle post request:

public HttpResponseMessage PostPerson(Person person)
{
    if (ModelState.IsValid)
    {
        _repo.UpdateOrAdd(person);

        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, person);
        string key = string.Format(
            "{0}={1},{2}={3}",
            "FirstName", ODataUriUtils.ConvertToUriLiteral(person.FirstName, Microsoft.Data.OData.ODataVersion.V3),
            "LastName", ODataUriUtils.ConvertToUriLiteral(person.LastName, Microsoft.Data.OData.ODataVersion.V3));
        response.Headers.Location = new Uri(Url.ODataLink(
            new EntitySetPathSegment("People"),
            new KeyValuePathSegment(key)));
        return response;
    }
    else
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }
}

Hope it helps.

 

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
2026春节习俗大全
2026春节习俗大全

本专题整合了2026春节习俗大全,阅读专题下面的文章了解更多详细内容。

68

2026.02.11

Yandex网页版官方入口使用指南_国际版与俄罗斯版访问方法解析
Yandex网页版官方入口使用指南_国际版与俄罗斯版访问方法解析

本专题全面整理了Yandex搜索引擎的官方入口信息,涵盖国际版与俄罗斯版官网访问方式、网页版直达入口及免登录使用说明,帮助用户快速、安全地进入Yandex官网,高效使用其搜索与相关服务。

200

2026.02.11

虫虫漫画网页版入口与免费阅读指南_正版漫画全集在线查看方法
虫虫漫画网页版入口与免费阅读指南_正版漫画全集在线查看方法

本专题系统整理了虫虫漫画官网及网页版最新入口,涵盖免登录观看、正版漫画全集在线阅读方式,并汇总稳定可用的访问渠道,帮助用户快速找到虫虫漫画官方页面,轻松在线阅读各类热门漫画内容。

40

2026.02.11

Docker容器化部署与DevOps实践
Docker容器化部署与DevOps实践

本专题面向后端与运维开发者,系统讲解 Docker 容器化技术在实际项目中的应用。内容涵盖 Docker 镜像构建、容器运行机制、Docker Compose 多服务编排,以及在 DevOps 流程中的持续集成与持续部署实践。通过真实场景演示,帮助开发者实现应用的快速部署、环境一致性与运维自动化。

4

2026.02.11

Rust异步编程与Tokio运行时实战
Rust异步编程与Tokio运行时实战

本专题聚焦 Rust 语言的异步编程模型,深入讲解 async/await 机制与 Tokio 运行时的核心原理。内容包括异步任务调度、Future 执行模型、并发安全、网络 IO 编程以及高并发场景下的性能优化。通过实战示例,帮助开发者使用 Rust 构建高性能、低延迟的后端服务与网络应用。

1

2026.02.11

Spring Boot企业级开发与MyBatis Plus实战
Spring Boot企业级开发与MyBatis Plus实战

本专题面向 Java 后端开发者,系统讲解如何基于 Spring Boot 与 MyBatis Plus 构建高效、规范的企业级应用。内容涵盖项目架构设计、数据访问层封装、通用 CRUD 实现、分页与条件查询、代码生成器以及常见性能优化方案。通过完整实战案例,帮助开发者提升后端开发效率,减少重复代码,快速交付稳定可维护的业务系统。

6

2026.02.11

包子漫画网页版入口与全集阅读指南_正版免费漫画快速访问方法
包子漫画网页版入口与全集阅读指南_正版免费漫画快速访问方法

本专题汇总了包子漫画官网和网页版入口,提供最新章节抢先看方法、正版免费阅读指南,以及稳定访问方式,帮助用户快速直达包子漫画页面,无广告畅享全集漫画内容。

159

2026.02.10

MC.JS网页版快速畅玩指南_MC.JS官网在线入口及免安装体验方法
MC.JS网页版快速畅玩指南_MC.JS官网在线入口及免安装体验方法

本专题汇总了MC.JS官网入口和网页版快速畅玩方法,提供免安装访问、不同版本(1.8.8、1.12.8)在线体验指南,以及正版网页端操作说明,帮助玩家轻松进入MC.JS世界,实现即时畅玩与高效体验。

89

2026.02.10

谷歌邮箱网页版登录与注册全指南_Gmail账号快速访问与安全操作教程
谷歌邮箱网页版登录与注册全指南_Gmail账号快速访问与安全操作教程

本专题汇总了谷歌邮箱网页版的最新登录入口和注册方法,详细提供官方账号快速访问方式、网页版操作教程及安全登录技巧,帮助用户轻松管理Gmail邮箱账户,实现高效、安全的邮箱使用体验。

78

2026.02.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
ASP.NET参考手册
ASP.NET参考手册

共0课时 | 0人学习

传播智客ASP.NET中级系列视频教程
传播智客ASP.NET中级系列视频教程

共33课时 | 6.5万人学习

传播智客ASP.NET高级系列视频教程
传播智客ASP.NET高级系列视频教程

共34课时 | 6.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号