在 models 和 services 项目中安装 NuGet 依赖库: MongoDB.Driver . 我安装的最新版: 2.8.1 版本
Install-Package MongoDB.Driver -Version {VERSION}
添加实体模型类, 添加对应的 service 操作类
- BaseModel:
- using System;
- using MongoDB.Bson;
- using MongoDB.Bson.Serialization.Attributes;
- namespace MongoDBDemo.Models
- {
- public class BaseModel
- {
- [BsonId] // 标记主键
- [BsonRepresentation(BsonType.ObjectId)] // 参数类型 , 无需赋值
- public string Id { get; set; }
- [BsonElement(nameof(CreateDateTime))] // 指明数据库中字段名为 CreateDateTime
- public DateTime CreateDateTime { get; set; }
- //[BsonElement(nameof(IsDelete))]
- public bool IsDelete { get; set; }
- public BaseModel()
- {
- CreateDateTime = DateTime.Now;
- IsDelete = false;
- }
- }
- }
- Student:
- namespace MongoDBDemo.Models
- {
- public class Student : BaseModel
- {
- public string Name { get; set; }
- public int Age { get; set; }
- }
- }
- BaseService:
- using Microsoft.Extensions.Configuration;
- using MongoDB.Driver;
- using MongoDBDemo.Models;
- using System.Collections.Generic;
- namespace MongoDBDemo.Services
- {
- public class BaseService where T : BaseModel
- {
- private readonly IMongoCollection _collection; // 数据表操作对象
- ///
- /// 构造函数
- ///
- ///
- /// 表名
- public BaseService(IConfiguration config, string tableName)
- {
- var client = new MongoClient(config.GetConnectionString("MongoDBDemo")); // 获取链接字符串
- var database = client.GetDatabase(config.GetSection("MongoDBSetting:DBName").Value); // 数据库名 (不存在自动创建)
- // 获取对特定数据表集合中的数据的访问
- _collection = database.GetCollection(tableName); // (不存在自动创建)
- }
- //Find - 返回集合中与提供的搜索条件匹配的所有文档.
- //InsertOne - 插入提供的对象作为集合中的新文档.
- //ReplaceOne - 将与提供的搜索条件匹配的单个文档替换为提供的对象.
- //DeleteOne - 删除与提供的搜索条件匹配的单个文档.
- ///
- /// 获取所有
- ///
- ///
- public List Get()
- {
- return _collection.Find(T => true).ToList();
- }
- ///
- /// 获取单个
- ///
- ///
- ///
- public T Get(string id)
- {
- return _collection.Find(T => T.Id == id).FirstOrDefault();
- }
- ///
- /// 创建
- ///
- ///
- ///
- public T Create(T T)
- {
- _collection.InsertOne(T);
- return T;
- }
- ///
- /// 更新
- ///
- ///
- ///
- public void Update(string id, T TIn)
- {
- _collection.ReplaceOne(T => T.Id == id, TIn);
- }
- ///
- /// 删除
- ///
- ///
- public void Remove(T TIn)
- {
- _collection.DeleteOne(T => T.Id == TIn.Id);
- }
- ///
- /// 根据 id 删除
- ///
- ///
- public void Remove(string id)
- {
- _collection.DeleteOne(T => T.Id == id);
- }
- }
- }
- StudentService:
- using Microsoft.Extensions.Configuration;
- using MongoDBDemo.Models;
- namespace MongoDBDemo.Services
- {
- public class StudentService : BaseService
- {
- public StudentService(IConfiguration config) : base(config, nameof(Student))
- {
- }
- }
- }
上层写好后, 需在 web 层 Startup 类中配置注入 service 注入以便在控制中使用 service 操作 MongoDB
services.AddScoped(); // 注入 service 服务
注入 service 后在控制器试一下好不好使, 运行项目后是好使的
HomeController 控制器代码:
- public class HomeController : Controller
- {
- private readonly StudentService _studentService;
- public HomeController(StudentService studentService) // 构造函数注入
- {
- _studentService = studentService;
- }
- public IActionResult Index()
- {
- return View();
- }
- #region CRUD
- ///
- /// 获取所有
- ///
- ///
- public ActionResult> Get()
- {
- return _studentService.Get();
- }
- ///
- /// 根据 id 获取
- ///
- ///
- ///
- [HttpGet("{id}")]
- public ActionResult Get(string id)
- {
- var Student = _studentService.Get(id);
- if (Student == null)
- {
- return NotFound();
- }
- return Student;
- }
- ///
- /// 添加
- ///
- ///
- ///
- public ActionResult Create(Student Student)
- {
- _studentService.Create(Student);
- return Ok();
- }
- ///
- /// 更新
- ///
- ///
- ///
- ///
- public IActionResult Update(string id, Student StudentIn)
- {
- var Student = _studentService.Get(id);
- if (Student == null)
- {
- return NotFound();
- }
- _studentService.Update(id, StudentIn);
- return NoContent();
- }
- ///
- /// 删除
- ///
- ///
- ///
- public IActionResult Delete(string id)
- {
- var Student = _studentService.Get(id);
- if (Student == null)
- {
- return NotFound();
- }
- _studentService.Remove(Student.Id);
- return NoContent();
- }
- #endregion
- public IActionResult Privacy()
- {
- return View();
- }
- [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
- public IActionResult Error()
- {
- return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
- }
- }
试一下添加删除, 都是好使的:
完结. 参考文档: https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio
来源: https://www.2cto.com/kf/201905/810248.html