文档菜单
文档首页
/ / /
C#/.NET
/

使用 MongoDB 中的 OData

本页内容

  • 概述
  • 示例数据
  • 教程
  • 安装依赖项
  • 定义您的模型
  • 创建 OData 控制器
  • 配置 OData 服务
  • 运行应用程序
  • 查询数据
  • 更多信息

OData(开放数据协议)是一种标准化的协议,用于构建和消费RESTful API,允许通过HTTP请求查询和操作数据。它提供了一种统一的方式来公开和交互来自多个源的数据。

在本教程中,您将学习如何将OData集成到您的MongoDB应用程序中。

本教程使用sample_restaurants.restaurants 集合来自Atlas 示例数据集。要了解如何创建免费的MongoDB Atlas集群并加载示例数据集,请参阅快速入门.

1

创建一个名为 ODataExample 的新 ASP.Net 应用程序,并安装 .NET/C# 驱动程序。您可以通过在您的 IDE 中使用 NuGet 包管理器或通过在 .NET CLI 中运行以下命令来安装驱动程序:

dotnet add package MongoDB.Driver

然后,通过 NuGet 包管理器或通过运行以下命令在 .NET CLI 中安装 MongoDB.AspNetCore.OData NuGet 包:

dotnet add package MongoDB.AspNetCore.OData
2

在您的解决方案中创建一个新的文件夹,名为 Models,并将以下 Restaurant.csAddress.csGradeEntry.cs 文件复制到该文件夹中

public class Restaurant
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }
}
public class Address
{
public string Building { get; set; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
}
public class GradeEntry
{
public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }
}

注意

restaurants 集合中的文档使用蛇形命名约定。本指南中的示例使用 ConventionPack 将集合字段反序列化为 Pascal 案,并将它们映射到 Restaurant 类的属性。

有关自定义序列化的更多信息,请参阅 自定义序列化。

3

在您的解决方案中创建一个名为 Controllers 的新文件夹,并添加一个名为 RestaurantsController.cs 的新控制器文件。将以下代码复制到文件中

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Routing.Controllers;
using MongoDB.AspNetCore.OData;
using MongoDB.Driver;
using ODataTest.Models;
namespace ODataTest.Controllers;
public class RestaurantsController : ODataController
{
private readonly IQueryable<Restaurant> _restaurants;
public RestaurantsController(IMongoClient client)
{
var database = client.GetDatabase("sample_restaurants");
_restaurants = database.GetCollection<Restaurant>("restaurants")
.AsQueryable();
}
// Registers Get endpoint and sets max documents to 5
[MongoEnableQuery(PageSize = 5)]
public ActionResult<IEnumerable<Restaurant>> Get()
{
return Ok(_restaurants);
}
}

此代码执行以下操作

  • 创建一个构造函数,用于连接到MongoDB,并获取 restaurants 集合。

  • 创建一个 Get 端点,返回集合中的所有餐厅。

  • 指定 MongoEnableQuery 属性以启用 Get 端点的查询。

  • MongoEnableQuery 上指定 PageSize 属性,将返回的文档数量限制为 5

4

将以下代码粘贴到您的 Program.cs 文件中,以配置OData服务和映射控制器端点。

using Microsoft.AspNetCore.OData;
using Microsoft.OData.ModelBuilder;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using ODataTest.Models;
var builder = WebApplication.CreateBuilder(args);
// Registers a convention pack to convert fields to camel case
var camelCaseConvention = new ConventionPack {
new CamelCaseElementNameConvention()
};
ConventionRegistry.Register(
"CamelCase", camelCaseConvention, type => true);
builder.Services.AddSingleton<IMongoClient>(
new MongoClient("<Your connection URI>"));
// Registers the Restaurants entity and sets the Id field as the key
var modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<Restaurant>("Restaurants");
modelBuilder.EntityType<Restaurant>().HasKey(r => r.Id);
// Adds OData and specify query capabilities
builder.Services.AddControllers().AddOData(
options => options.Select()
.AddRouteComponents("odata", modelBuilder.GetEdmModel())
);
var app = builder.Build();
app.UseRouting();
app.MapControllers();
app.Run();

注意

<"Your connection URI"> 占位符替换为您的MongoDB连接字符串。

此代码执行以下操作

  • 创建一个新的 MongoClient 实例并将其注册为依赖注入容器中的单例。

  • 定义实体数据模型 (EDM),并将 Restaurants 注册为具有键 Id 的实体集。

  • 添加OData服务并启用 Select() 查询操作。

  • 使用 AddRouteComponents() 方法注册路由。

  • 调用 UseRouting()MapControllers() 方法来匹配传入的HTTP请求并将它们路由到适当的端点。

注意

.NET/C# 驱动程序不支持使用 $apply 查询操作进行 OData-Aggregation。

5

使用您的IDE运行应用程序,或在您的项目根目录的shell中运行以下命令

dotnet run ODataExample.csproj

应用程序运行后,您的终端显示类似于以下内容的输出

info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5183
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: <Path to your project>

提示

运行应用程序后,您的IDE可能会自动打开一个浏览器窗口,显示应用程序运行的URL,并显示“找不到页面”错误。这是预期的,因为应用程序只配置了一个“获取”端点。

6

要查询数据,导航到应用程序中指定的“获取”端点。为此,请打开浏览器并导航到先前步骤中终端输出的“localhost” URL。然后,添加“获取”端点的路由:/odata/Restaurants。例如,如果应用程序在localhost:5183上运行,请导航到http://localhost:5183/odata/Restaurants

如果成功,浏览器将显示集合中的5家餐厅,格式为JSON。输出类似于以下内容

{
"@odata.context": "http://localhost:5183/odata/$metadata#Restaurants",
"value": [
{
"Name": "Glorious Food",
"RestaurantId": "40361521",
"Cuisine": "American",
"Borough": "Manhattan",
"Id": "...",
"Address": {
"Building": "522",
"Coordinates": [-73.95171, 40.767461],
"Street": "East 74 Street",
"ZipCode": "10021"
},
"Grades": [
...
]
},
...
]
}

要了解更多关于ASP.NET Core OData的信息,请参阅Microsoft OData文档。

要了解更多关于OData的信息,请参阅OData文档。

返回

副本集操作