ASP.NET Core OData 实践——Lesson6使用Action(C#)
大纲
- 支持的接口
- 主要模型设计
- 控制器设计
- 数据源
- 调用Action(Post)
- 调用绑定的Action
- 调用绑定到基类类型EntitySet的Action
- 调用绑定到基类类型Entity的Action
- 调用绑定到特定派生类类型EntitySet的Action
- 调用绑定到特定派生类类型Entity的Action
- 调用未绑定的Action
- 主程序
- 服务文档
- 模型元文档
- 代码地址
- 参考资料
本文是一个基于 ASP.NET Core OData 的 Web API 示例,主要演示了如何通过 OData Action 实现批量或单个对象的业务操作,如发放礼品、奖金和工资计算。
在 OData 中,Action 是一种用于执行带有副作用(如修改数据、批量操作等)业务逻辑的服务端操作。与标准的 CRUD(增删改查)不同,Action 可以实现更复杂的业务场景,比如批量发放礼品、奖金、审批等。
支持的接口
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}|{singleton}/{action} | 调用绑定到EntitySet或者Singleton的Action |
POST | ~/{entityset}|{singleton}/{cast}/{action} | 调用绑定到EntitySet或者Singleton的特定派生类型的Action |
POST | ~/{entityset}/{key}/{action} | 通过指定Key调用绑定到Entity的Action |
POST | ~/{entityset}/{key}/{cast}/{action} | 通过指定Keyd调用绑定到特定派生类型的Action |
POST | ~/{action} | 调用非绑定Action |
主要模型设计
在项目下新增Models文件夹,并添加Employee和Manager类。
Employee的Property解释如下:
- Id
- 类型:int
- 说明:员工的唯一标识符。通常作为主键,用于区分不同员工对象。
- Name
- 类型:required string
- 说明:员工姓名。required 关键字表示在创建 Employee 实例时必须赋值,保证数据完整性。
- SwagGift
- 类型:string?(可空字符串)
- 说明:员工获得的纪念品或福利礼物。例如,公司年会、节日等场合发放的礼品。可为 null,表示该员工可能还未获得礼物。
namespace Lesson6.Models
{public class Employee{public int Id { get; set; }public required string Name { get; set; }public string? SwagGift { get; set; }}
}
Manager 类继承自 Employee,意味着 Manager 拥有 Employee 的所有属性(如 Id、Name、SwagGift)。同时它也定义了自己的Property:
- Bonus
- 类型:decimal
- 说明:经理的奖金。该属性是 Manager 独有的,普通员工没有此属性。
- 用途:用于记录和查询经理的额外奖励,适合 OData 查询、奖金统计、业务逻辑处理等。
namespace Lesson6.Models
{public class Manager : Employee{public decimal Bonus { get; set; }}
}
控制器设计
在项目中新增Controller文件夹,然后添加CompanyController类。该类注册于ODataController,以便拥有如下能力:
- OData 路由支持
继承 ODataController 后,控制器自动支持 OData 路由(如 /odata/Shapes(1)),可以直接响应 OData 标准的 URL 路径和操作。 - OData 查询参数支持
可以使用 [EnableQuery] 特性,自动支持 $filter、$select、$orderby、$expand 等 OData 查询参数,无需手动解析。 - OData 响应格式
返回的数据会自动序列化为 OData 标准格式(如 JSON OData),方便前端或其他系统消费。 - OData Delta 支持
支持 Delta<T>、DeltaSet<T> 等类型,便于实现 PATCH、批量 PATCH 等 OData 特有的部分更新操作。 - 更丰富的 OData 语义
继承后可方便实现实体集、实体、导航属性、复杂类型等 OData 语义,提升 API 的表达能力。
using Lesson6.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;namespace Lesson6.Controllers
{public class EmployeesController : ODataController{}
}
下面我们在该类中填充逻辑。
数据源
private static List<Employee> employees =[new Employee { Id = 1, Name = "Employee 1" },new Employee { Id = 2, Name = "Employee 2" },new Employee { Id = 3, Name = "Employee 3" },new Employee { Id = 4, Name = "Employee 4" },new Manager { Id = 5, Name = "Employee 5" },new Manager { Id = 6, Name = "Employee 6" }];
调用Action(Post)
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}|{singleton}/{function} | 调用绑定到EntitySet或者Singleton的Action |
POST | ~/{entityset}|{singleton}/{cast}/{function} | 调用绑定到EntitySet或者Singleton的特定派生类型的Action |
POST | ~/{entityset}/{key}/{function} | 通过指定Key调用绑定到Entity的Action |
POST | ~/{entityset}/{key}/{cast}/{function} | 通过指定Keyd调用绑定到特定派生类型的Action |
POST | ~/{function} | 调用非绑定Action |
调用绑定的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}|{singleton}/{function} | 调用绑定到EntitySet或者Singleton的Action |
POST | ~/{entityset}|{singleton}/{cast}/{function} | 调用绑定到EntitySet或者Singleton的特定派生类型的Action |
POST | ~/{entityset}/{key}/{function} | 通过指定Key调用绑定到Entity的Action |
POST | ~/{entityset}/{key}/{cast}/{function} | 通过指定Keyd调用绑定到特定派生类型的Action |
bound action(绑定操作)在 OData 中有以下特点:
- 与实体或实体集绑定
- bound action 必须绑定到某个实体类型(如 Employee)或实体集(如 Employees)。
- 例如:为单个员工发放奖金的操作可以绑定到 Employee,批量发放可以绑定到 Employees 集合。
- 调用时需指定绑定对象
- 路由中必须包含实体或集合。例如:
- 单实体:POST /odata/Employees(1)/Default.ConferBonus
- 实体集:POST /odata/Employees/Default.ConferBonuses
- 第一个参数为绑定类型
- 在 EDMX 元数据中,bound action 的第一个参数是 bindingParameter,类型为绑定的实体或集合。
- 常用于与特定数据相关的业务操作
- 适合实现“对某个对象/集合做某事”的业务逻辑,如发放奖金、批量更新、状态变更等。
- OData 路由自动识别
- OData 框架会根据 action 绑定类型自动生成对应的路由和元数据。
调用绑定到基类类型EntitySet的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}|{singleton}/{function} | 调用绑定到EntitySet或者Singleton的Action |
下面方法用于为所有员工(EntitySet)批量发放纪念品(SwagGift)。
[HttpPost]public ActionResult ConferSwagGifts(ODataActionParameters parameters){if (parameters != null && parameters.TryGetValue("SwagGift", out object? swag) && swag != null){foreach (var employee in employees){employee.SwagGift = swag.ToString();}}else{return BadRequest();}return Ok();}
- Request
curl --location 'http://localhost:5119/odata/Employees/ConferSwagGifts' \
--header 'Content-Type: application/json' \
--data '{"SwagGift": "Mug"
}'
调用绑定到基类类型Entity的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}/{key}/{function} | 通过指定Key调用绑定到Entity的Action |
下面方法用于为指定员工发放纪念品(SwagGift)
[HttpPost]public ActionResult ConferSwagGift([FromRoute] int key, ODataActionParameters parameters){if (parameters != null && parameters.TryGetValue("SwagGift", out object? swag) && swag != null){var employee = employees.SingleOrDefault(d => d.Id.Equals(key));if (employee == null){return NotFound();}employee.SwagGift = swag.ToString();}else{return BadRequest();}return Ok();}
- Request
curl --location 'http://localhost:5119/odata/Employees(1)/ConferSwagGift' \
--header 'Content-Type: application/json' \
--data '{"SwagGift": "Gaiter"
}'
调用绑定到特定派生类类型EntitySet的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}|{singleton}/{cast}/{function} | 调用绑定到EntitySet或者Singleton的特定派生类型的Action |
下面方法用于为所有经理(Manager)批量发放奖金(Bonus)。
[HttpPost]public ActionResult ConferBonusesOnCollectionOfManager(ODataActionParameters parameters){if (parameters != null && parameters.TryGetValue("Bonus", out object? bonus) && bonus != null){var managers = employees.OfType<Manager>();foreach (var manager in managers){manager.Bonus = Convert.ToDecimal(bonus);}}else{return BadRequest();}return Ok();}
- Request
curl --location 'http://localhost:5119/odata/Employees/Lesson6.Models.Manager/ConferBonuses' \
--header 'Content-Type: application/json' \
--data '{"Bonus": 130
}'
调用绑定到特定派生类类型Entity的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{entityset}/{key}/{cast}/{function} | 通过指定Keyd调用绑定到特定派生类型的Action |
下面方法用于为指定的经理(Manager)发放奖金(Bonus)
[HttpPost]public ActionResult ConferBonusOnManager([FromRoute] int key, ODataActionParameters parameters){if (parameters != null && parameters.TryGetValue("Bonus", out object? bonus) && bonus != null){var manager = employees.OfType<Manager>().SingleOrDefault(d => d.Id.Equals(key));if (manager == null){return NotFound();}manager.Bonus = Convert.ToDecimal(bonus);}else{return BadRequest();}return Ok();}
- Request
curl --location 'http://localhost:5119/odata/Employees(5)/Lesson6.Models.Manager/ConferBonus' \
--header 'Content-Type: application/json' \
--data '{"Bonus": 70
}'
调用未绑定的Action
Request Method | Route Template | 说明 |
---|---|---|
POST | ~/{function} | 调用非绑定Action |
unbound action(非绑定操作)在 OData 中有以下特点:
- 不依赖于实体或实体集
- unbound action 不是挂在某个实体类型或集合上的,而是全局可用。
- 例如:ComputeSalary 可以直接通过 /odata/ComputeSalary 调用。
- 调用方式简单
- 直接通过 OData 路由访问,无需指定实体或集合。
- 例:POST /odata/ComputeSalary
- 参数和返回值自定义
- 可以有任意参数和返回类型,不受实体模型约束,适合实现全局业务操作、工具类服务等。
- 在 EDMX 中有 ActionImport
- 在元数据(EDMX)中,unbound action 会通过 节点暴露,区别于 bound action 的绑定参数。
为了区别之前的绑定Action,我们新定义一个DefaultController ,用来承载未绑定Action。
下面方法用于根据传入的时薪(hourlyRate)和工时(hoursWorked)计算工资,并返回结果。
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Formatter;
using Microsoft.AspNetCore.OData.Routing.Controllers;namespace Lesson6.Controllers
{public class DefaultController : ODataController{[HttpPost("odata/ComputeSalary")]public ActionResult<decimal> ComputeSalary(ODataActionParameters parameters){if (parameters == null){return BadRequest();}if (!parameters.TryGetValue("hourlyRate", out var hourlyRateAsObject)|| hourlyRateAsObject == null|| !decimal.TryParse(hourlyRateAsObject.ToString(), out var hourlyRate)){return BadRequest();}if (!parameters.TryGetValue("hoursWorked", out var hoursWorkedAsObject)|| hoursWorkedAsObject == null|| !int.TryParse(hoursWorkedAsObject.ToString(), out var hoursWorked)){return BadRequest();}return hourlyRate * hoursWorked;}}
}
- Request
curl --location 'http://localhost:5119/odata/ComputeSalary' \
--header 'Content-Type: application/json' \
--data '{"hourlyRate": 17.0,"hoursWorked": 40
}'
主程序
下面代码中:
employeeEntityType.Collection.Action("ConferSwagGifts").Parameter<string>("SwagGift");
将ConferSwagGifts
方法绑定到Employees这个EntitySet上。
employeeEntityType.Action("ConferSwagGift").Parameter<string>("SwagGift");
将ConferSwagGift
方法绑定到Employee这个Entity上。
managerEntityType.Collection.Action("ConferBonuses").Parameter<decimal>("Bonus");
将ConferBonuses
绑定到Manager这个派生类的EntitySet上。
managerEntityType.Action("ConferBonus").Parameter<decimal>("Bonus");
将ConferBonus
绑定到Manager这个派生类的Entity上。
ComputeSalary
是为绑定的Action。
using Lesson6.Models;
using Microsoft.AspNetCore.OData;
using Microsoft.OData.ModelBuilder;
using Microsoft.OData.Edm;var builder = WebApplication.CreateBuilder(args);// 提取 OData EDM 模型构建为方法,便于维护和扩展
static IEdmModel GetEdmModel()
{var modelBuilder = new ODataConventionModelBuilder();modelBuilder.EntitySet<Employee>("Employees");var employeeEntityType = modelBuilder.EntitySet<Employee>("Employees").EntityType;employeeEntityType.Collection.Action("ConferSwagGifts").Parameter<string>("SwagGift");employeeEntityType.Action("ConferSwagGift").Parameter<string>("SwagGift");var managerEntityType = modelBuilder.EntityType<Manager>();managerEntityType.Collection.Action("ConferBonuses").Parameter<decimal>("Bonus");managerEntityType.Action("ConferBonus").Parameter<decimal>("Bonus");var computeSalaryFunction = modelBuilder.Action("ComputeSalary");computeSalaryFunction.Parameter<decimal>("hourlyRate");computeSalaryFunction.Parameter<int>("hoursWorked");computeSalaryFunction.Returns<decimal>();return modelBuilder.GetEdmModel();
}// 添加 OData 服务和配置
builder.Services.AddControllers().AddOData(options =>options.Select().Filter().OrderBy().Expand().Count().SetMaxTop(null).AddRouteComponents("odata", GetEdmModel())
);var app = builder.Build();app.UseRouting();app.MapControllers();app.Run();
服务文档
- Request
curl --location 'http://localhost:5119/odata'
- Response
{"@odata.context": "http://localhost:5119/odata/$metadata","value": [{"name": "Employees","kind": "EntitySet","url": "Employees"}]
}
模型元文档
- Request
curl --location 'http://localhost:5119/odata/$metadata'
- Response
<?xml version="1.0" encoding="utf-8"?>
<edmx:Edmx Version="4.0" xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx"><edmx:DataServices><Schema Namespace="Lesson6.Models" xmlns="http://docs.oasis-open.org/odata/ns/edm"><EntityType Name="Employee"><Key><PropertyRef Name="Id" /></Key><Property Name="Id" Type="Edm.Int32" Nullable="false" /><Property Name="Name" Type="Edm.String" Nullable="false" /><Property Name="SwagGift" Type="Edm.String" /></EntityType><EntityType Name="Manager" BaseType="Lesson6.Models.Employee"><Property Name="Bonus" Type="Edm.Decimal" Nullable="false" Scale="variable" /></EntityType></Schema><Schema Namespace="Default" xmlns="http://docs.oasis-open.org/odata/ns/edm"><Action Name="ConferSwagGifts" IsBound="true"><Parameter Name="bindingParameter" Type="Collection(Lesson6.Models.Employee)" /><Parameter Name="SwagGift" Type="Edm.String" /></Action><Action Name="ConferSwagGift" IsBound="true"><Parameter Name="bindingParameter" Type="Lesson6.Models.Employee" /><Parameter Name="SwagGift" Type="Edm.String" /></Action><Action Name="ConferBonuses" IsBound="true"><Parameter Name="bindingParameter" Type="Collection(Lesson6.Models.Manager)" /><Parameter Name="Bonus" Type="Edm.Decimal" Nullable="false" Scale="variable" /></Action><Action Name="ConferBonus" IsBound="true"><Parameter Name="bindingParameter" Type="Lesson6.Models.Manager" /><Parameter Name="Bonus" Type="Edm.Decimal" Nullable="false" Scale="variable" /></Action><Action Name="ComputeSalary"><Parameter Name="hourlyRate" Type="Edm.Decimal" Nullable="false" Scale="variable" /><Parameter Name="hoursWorked" Type="Edm.Int32" Nullable="false" /><ReturnType Type="Edm.Decimal" Nullable="false" Scale="variable" /></Action><EntityContainer Name="Container"><EntitySet Name="Employees" EntityType="Lesson6.Models.Employee" /><ActionImport Name="ComputeSalary" Action="Default.ComputeSalary" /></EntityContainer></Schema></edmx:DataServices>
</edmx:Edmx>
其组成和解释如下:
- 实体类型定义
- Employee
- <EntityType Name=“Employee”>:定义了 Employee 实体。
- <Key><PropertyRef Name=“Id” /></Key>:主键为 Id。
- <Property Name=“Id” Type=“Edm.Int32” Nullable=“false” />:Id,int 类型,必填。
- <Property Name=“Name” Type=“Edm.String” Nullable=“false” />:Name,string 类型,必填。
- <Property Name=“SwagGift” Type=“Edm.String” />:SwagGift,纪念品,可空字符串。
- Manager
- <EntityType Name=“Manager” BaseType=“Lesson6.Models.Employee”>:Manager 继承自 Employee。
- <Property Name=“Bonus” Type=“Edm.Decimal” Nullable=“false” Scale=“variable” />:Bonus,奖金,decimal 类型,必填。
- Action(操作)定义
- ConferSwagGifts
- 绑定到 Employee 集合(IsBound=“true”,Type=“Collection(Lesson6.Models.Employee)”)。
- 参数:SwagGift(string),为所有员工批量发放纪念品。
- ConferSwagGift
- 绑定到单个 Employee。
- 参数:SwagGift(string),为指定员工发放纪念品。
- ConferBonuses
- 绑定到 Manager 集合。
- 参数:Bonus(decimal),为所有经理批量发放奖金。
- ConferBonus
- 绑定到单个 Manager。
- 参数:Bonus(decimal),为指定经理发放奖金。
- ComputeSalary
- 非绑定(unbound)Action。
- 参数:hourlyRate(decimal)、hoursWorked(int)。
- 返回值:decimal,计算工资(时薪 × 工时)。
- 通过 <ActionImport> 暴露为全局操作,可直接调用。
- 实体容器与实体集
- <EntityContainer Name=“Container”>:OData 服务的根容器。
- <EntitySet Name=“Employees” EntityType=“Lesson6.Models.Employee” />:定义了 Employees 实体集,类型为 Employee(包含 Manager)。
- <ActionImport Name=“ComputeSalary” … />:将 ComputeSalary 作为全局操作暴露,允许通过 /odata/ComputeSalary 直接调用。
代码地址
https://github.com/f304646673/odata/tree/main/csharp/Lesson/Lesson6
参考资料
- https://learn.microsoft.com/en-us/odata/webapi-8/fundamentals/action-routing?tabs=net60%2Cvisual-studio