【问题标题】:OData v4 Web API support for Composite Keys复合键的 OData v4 Web API 支持
【发布时间】:2015-02-16 16:24:43
【问题描述】:

我正在使用 WebAPI 和 OData v4 构建 OData Web 服务。

通过覆盖 EntityRoutingConvention 的 SelectAction 方法,我能够让服务支持复合键。但是,在以前版本的 OData 中,这不是必需的。我个人认为这很混乱,我觉得我在重新发明轮子。

还有其他方法吗?

【问题讨论】:

    标签: odata asp.net-web-api2 composite-key


    【解决方案1】:

    使用属性路由。

    一个例子:

    型号:

    public class Product
    {
        [Key]
        public int ID { get; set; }
    
        [Key]
        public string Name { get; set; }
    }
    

    使用复合键识别实体的控制器方法:

    [EnableQuery]
    [ODataRoute("Products(ID={key1},Name={key2})")]
    public IHttpActionResult Get([FromODataUri] int key1, [FromODataUri] string key2)
    {
        // You business logic for retrieving the entity from your storage using the two keys and return
    }
    

    索取样品:

    GET http://host/service/Products(ID=1,Name='Car')
    

    无需重写路由约定。

    【讨论】:

    • 谢谢,我会试试这个。这也支持导航属性吗? [ODataRoute("Products(ID={key1},Name={key2})/NavigationProperty")]
    • @FrancescoFerraioli 是的。
    【解决方案2】:

    您可以使用开箱即用的前缀“key”来做到这一点:

    [EnableQuery]
    public IHttpActionResult Get([FromODataUri] int keyID, [FromODataUri] string keyName)
    {
        // You business logic for retrieving the entity from your storage using the two keys and return
    }
    

    我刚刚检查了 Microsoft.AspNet.OData v7.0.1

    你可以找到它的来源https://github.com/OData/WebApi/blob/master/samples/AspNetCoreODataSample.Web/Controllers/PeopleController.cs

    【讨论】:

    • 这对我有用,但你有文档支持吗?将其添加到您的答案中是个好主意。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 2015-07-14
    • 2012-06-20
    • 2014-11-27
    • 2014-07-01
    • 1970-01-01
    相关资源
    最近更新 更多