当前位置: 首页 > news >正文

快速上手ASP .NET Core 8与MongoDB整合

话不多说,先了解一下MongoDB,在后端服务中选择一个数据库,是由最适合项目应用场景的架构决策所决定的。在做出决策前就需要了解和学习数据库的相关特性,从数据库官网学习了解它的特性是最适合不过的了。

MongoDB官方手册网站:MongoDB是什么? - 数据库手册 - MongoDB Docs

MongoDB .NET/C# 驱动程序手册网站:快速入门 - C#/.NET 驱动程序 v3.4 - MongoDB Docs

1、添加MongoDB.Driver

dotnet add package MongoDB.Driver

2、添加MongoDB配置信息到appsettings.json中

"MongoDBConfig": {"BooksCollectionName": "Book","DatabaseName": "BookStoreDB","ConnectionString": "mongodb://localhost:27017/",
}

3、创建MongoDB配置信息类

public class MongoDBConfig
{public string BookCollectionName { get; set; } = string.Empty;public string DatabaseName { get; set; } = string.Empty;public string ConnectionString { get; set; } = string.Empty;
}

4、创建实体类-Book

public class Book
{[BsonId][BsonRepresentation(BsonType.ObjectId)]public string Id { get; set; } = ObjectId.GenerateNewId().ToString();[BsonElement("Name")]public string BookName { get; set; } = string.Empty;public decimal Price { get; set; }public string Category { get; set; } = string.Empty;public string Author { get; set; } = string.Empty;[BsonDateTimeOptions(Kind = DateTimeKind.Local)]public DateTime CreationTime { get; set; } = DateTime.Now;
}

注:[BsonDateTimeOptions(Kind = DateTimeKind.Local)]必须要添加的,因为MongoDB写入时间是协调世界时(UTC),不加这样注解,查询出来结果会有时区误差。

5、创建自定义MongoDB上下文

public class MongoDBContext
{public IMongoCollection<Book> Books { get; }public MongoDBContext(MongoDBConfig mongodbConfig){if (mongodbConfig != null){if (string.IsNullOrEmpty(mongodbConfig.ConnectionString))throw new ArgumentException("MongoDB connection is not configured");var client = new MongoClient(mongodbConfig.ConnectionString);var database = client.GetDatabase(mongodbConfig.DatabaseName);Books = database.GetCollection<User>(mongodbConfig.BookCollectionName);}else{throw new ArgumentNullException(nameof(mongodbConfig));}}
}

6、创建自定义MongoDB扩展注入服务

public static class MongoDBServiceExtensions
{public static IServiceCollection AddMongoDB(this IServiceCollection services, IConfiguration configuration){services.Configure<MongoDBConfig>(configuration.GetSection("MongoDBConfig"));services.AddSingleton<MongoDBContext>(provider =>{var settings = configuration.GetSection("MongoDBConfig").Get<MongoDBConfig>();return settings == null? throw new InvalidOperationException("MongoDBConfig is not configured properly."): new MongoDBContext(settings);});return services;}
}

注:这里为什么会将MongoDBContext注册为单例服务,因为官方文档推荐单例模式

7、Program.cs文件中注入MongoDB

builder.Services.AddMongoDB(builder.Configuration);

8、使用MongoDB

[ApiController]
[Route("api/[controller]")]public class BookController : ControllerBase
{private readonly ILogger<BookController> _logger;private readonly MongoDBContext _mongodbContext;public BookController(MongoDBContext mongodbContext, ILogger<BookController> logger){_logger = logger;_mongodbContext = mongodbContext;}[HttpGet]public async Task<List<Book>> GetList(){return await _mongodbContext.Books.Find(_ => true).ToListAsync();}[HttpGet("{id:length(24)}")]public async Task<ActionResult<Book>> Get(string id){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}return book;}[HttpPost]public async Task<IActionResult> Post(Book newBook){await _mongodbContext.Books.InsertOneAsync(newBook);return CreatedAtAction(nameof(Get), new { id = newBook.Id }, newBook);}[HttpPut("{id:length(24)}")]public async Task<IActionResult> Update(string id, Book updatedBook){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}updatedBook.Id = book.Id;await _mongodbContext.Books.ReplaceOneAsync(x => x.Id == id, updatedBook); ;return NoContent();}[HttpDelete("{id:length(24)}")]public async Task<IActionResult> Delete(string id){var book = await _mongodbContext.Books.Find(x => x.Id == id).FirstOrDefaultAsync();if (book is null){return NotFound();}await _mongodbContext.Books.DeleteOneAsync(x => x.Id == id);return NoContent();}
}

 

http://www.lryc.cn/news/584406.html

相关文章:

  • Mac 电脑crontab执行定时任务【Python 实战】
  • 【保姆级喂饭教程】idea中安装Conventional Commit插件
  • Wsl/InstallDistro/Service/RegisterDistro/CreateVm/HCS/E_INVALIDARG
  • Android ViewBinding 使用与封装教程​​
  • Flutter 与 Android 的互通几种方式
  • 第35周—————糖尿病预测模型优化探索
  • 灰度发布过程中的异常处理
  • frp内网穿透下创建FTP(解决FTP“服务器回应不可路由的地址。使用服务器地址替代”错误)
  • Vue响应式原理五:响应式-自动收集依赖
  • 【Action帧简要分析】
  • 实验作业1+整理笔记截图
  • LLM 微调:从数据到部署的全流程实践与经验分享
  • TradePort 借助 Walrus 构建更高级的 NFT 市场
  • FPGA设计思想与验证方法学系列学习笔记001
  • 基于“SRP模型+”多技术融合在生态环境脆弱性评价模型构建、时空格局演变分析与RSEI 指数的生态质量评价及拓展应用
  • upload-labs靶场通关详解:第20关 /.绕过
  • 【计算机网络】HTTP1.0 HTTP1.1 HTTP2.0 QUIC HTTP3 究极总结
  • QT解析文本框数据——概述
  • 中国成人急性髓系白血病(非M3)诊疗指南(2021年版)
  • upload-labs靶场通关详解:第21关 数组绕过
  • Mysql分片:一致性哈希算法
  • 【Python】基于Python提取图片验证码
  • QTextCodec的功能及其在Qt5及Qt6中的演变
  • Qt Creator控件及其用途详细总结
  • Spring for Apache Pulsar->Reactive Support->Message Production
  • 生产环境CI/CD流水线构建与优化实践指南
  • 访问Windows服务器备份SQL SERVER数据库
  • 网安-解决pikachu-rce乱码问题
  • NFS文件存储及部署论坛(小白的“升级打怪”成长之路)
  • G5打卡——Pix2Pix算法