ASP.NET6 + Mongo + OData

2023-02-12 06:00:41

準備工作

  • Docker環境
  • Mongo資料庫
  • 設定Mongo資料庫

ASP.NET6 整合Mongo

安裝MongoDB.Driver

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
            }
    },
    "BookStoreDatabase": {
        "ConnectionString": "mongodb://localhost",
        "DatabaseName": "BookStore",
        "BooksCollectionName": "Books"
        },
    "AllowedHosts": "*"
}
public class BookStoreDatabaseSettings
{
    public string ConnectionString { get; set; } = null!;

    public string DatabaseName { get; set; } = null!;

    public string BooksCollectionName { get; set; } = null!;
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoExample.Models;

public class Book
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string? Id { get; set; }

    [BsonElement("Name")]
    public string BookName { get; set; } = null!; 
    
    public decimal Price { get; set; }

    public string Category { get; set; } = null!;

    public string Author { get; set; } = null!;
}
using MongoDB.Driver;
using MongoExample.Models;
using Microsoft.Extensions.Options;

namespace MongoExample.Services;

public class BookService
{
    private readonly IMongoCollection<Book> _bookCollection;

    public BookService(IOptions<BookStoreDatabaseSettings> bookStoreDatabaseSettings)
    {
        var mongoClient = new MongoClient("mongodb://admin:000000@localhost:27017");
        var mongoDatabase = mongoClient.GetDatabase(bookStoreDatabaseSettings.Value.DatabaseName);
        _bookCollection = mongoDatabase.GetCollection<Book>(bookStoreDatabaseSettings.Value.BooksCollectionName);
    }

    public async Task<List<Book>> GetBooksAsync() => await _bookCollection.Find(_ => true).ToListAsync();

    public async Task<Book> GetBookAsync(string id) => await _bookCollection.Find(x=>x.Id == id).FirstOrDefaultAsync();

    public async Task CreateAsync(Book book) => await _bookCollection.InsertOneAsync(book);

    public async Task UpdateAsync(string id, Book updatedBook) => await _bookCollection.ReplaceOneAsync(x=>x.Id == id, updatedBook);

    public async Task RemoveAsync(string id) => await _bookCollection.DeleteOneAsync(x=>x.Id ==id); 
}

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Query;
using MongoExample.Models;
using MongoExample.Services;

namespace MongoExample.Controllers;

[ApiController]
[Route("/api/[controller]")]
public class BooksController : ControllerBase
{
    private readonly BookService _bookService;

    public BooksController(BookService bookService)
    {
        this._bookService = bookService;
    }

    [HttpGet]
    [EnableQuery]
    public async Task<List<Book>> Get() => await _bookService.GetBooksAsync();

    [HttpGet("{id:length(24)}")]
    public async Task<ActionResult<Book>> GetBook(string id)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        return book;
    }

    [HttpPost]
    public async Task<ActionResult> Create(Book book)
    {
        await _bookService.CreateAsync(book);
        return CreatedAtAction("Get", new { id = book.Id }, book);
    }

    [HttpPut("{id:length(24)}")]
    public async Task<IActionResult> Update(string id, Book updatedBook)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        updatedBook.Id = book.Id;
        await _bookService.UpdateAsync(id, updatedBook);
        return NoContent();
    }

    [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> Delete(string id)
    {
        var book = await _bookService.GetBookAsync(id);
        if (book == null)
        {
            return NotFound();
        }

        await _bookService.RemoveAsync(id);
        return NoContent();
    }
}

ASP.NET6 整合OData

VS22022基於.NET6基礎上建立的asp.net core web api模板已經合併了Startup和Program類, 所有的服務注入,中介軟體注入都合併在了Program類中, 好久沒寫C#了,這個類這次變化有點大。
安裝OData

合併後的模板只有Program.cs類,沒有了Startup類,也就是之前的服務注入都是通過ConfigServices方法,IServiceCollection實現。 如果不習慣的話也可以自己手動建立一個Startup類,然後在Program類中呼叫該類。

using Microsoft.AspNetCore.OData;
using MongoExample.Models;
using MongoExample.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.Configure<BookStoreDatabaseSettings>(builder.Configuration.GetSection("BookStoreDatabase"));
builder.Services.AddSingleton<BookService>();
//這裡注入OData查詢方法
builder.Services.AddControllers().AddOData(options => options.Select().Filter().OrderBy());

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();

測試OData Query

查詢Category和BookName欄位
http://localhost:5220/api/books?$select=Category,BookName
響應JSON值

[{"Category":"Computer","BookName":"Design Patters"},{"Category":"Software","BookName":"Java In Action"},{"Category":"Software","BookName":"C# In Action"}]

查詢Category和BookName欄位並且用Category倒敘排列

[{"Category":"Software","BookName":"Java In Action"},{"Category":"Software","BookName":"C# In Action"},{"Category":"Computer","BookName":"Design Patters"}]