在 C# 中使用 OData 时,处理数据关联的方法与处理一般的数据关联类似。以下是一些基本步骤:
Customer 和 Order,它们之间存在一对多的关联。你需要为这两个实体定义模型类,如下所示:public class Customer { public int Id { get; set; } public string Name { get; set; } public List<Order> Orders { get; set; } } public class Order { public int Id { get; set; } public string OrderNumber { get; set; } public int CustomerId { get; set; } public Customer Customer { get; set; } } WebApiConfig.cs 文件中添加以下内容:config.MapODataServiceRoute( name: "ODataRoute", routePrefix: "api", model: GetModel(), routingConventions: new[] { new EntitySetRoutingConvention() }); WebApiConfig.cs 文件中添加以下内容:public static class WebApiConfig { public static void Register(HttpConfiguration config) { // ... 其他配置代码 ... config.Routes.MapODataRoute( name: "ODataRoute", routePrefix: "api", model: GetModel(), routingConventions: new[] { new EntitySetRoutingConvention() }); } private static IEdmModel GetModel() { ODataModelBuilder builder = new ODataModelBuilder(); builder.EntitySet<Customer>("Customers"); builder.EntitySet<Order>("Orders"); // 自定义关联查询 builder.Entity<Customer>().HasMany(c => c.Orders).WithRequired(o => o.Customer); return builder.GetEdmModel(); } } GET http://localhost:端口号/api/Customers?$expand=Orders 这将返回与每个客户关联的订单信息。