环境:Asp.Net Core Mvc 2.2,MongoDB 4.09
参考文档:http://mongodb.github.io/mongo-csharp-driver/ http://mongodb.github.io/mongo-csharp-driver/2.8/
创建 ASP.NET Core Mvc 项目
添加models,添加services
基本的结构就这样了
在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<T> where T : BaseModel { private readonly IMongoCollection<T> _collection; //数据表操作对象 /// <summary> /// 构造函数 /// </summary> /// <param name="config"></param> /// <param name="tableName">表名</param> 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<T>(tableName); // (不存在自动创建) } //Find<T> – 返回集合中与提供的搜索条件匹配的所有文档。 //InsertOne – 插入提供的对象作为集合中的新文档。 //ReplaceOne – 将与提供的搜索条件匹配的单个文档替换为提供的对象。 //DeleteOne – 删除与提供的搜索条件匹配的单个文档。 /// <summary> /// 获取所有 /// </summary> /// <returns></returns> public List<T> Get() { return _collection.Find(T => true).ToList(); } /// <summary> /// 获取单个 /// </summary> /// <param name="id"></param> /// <returns></returns> public T Get(string id) { return _collection.Find<T>(T => T.Id == id).FirstOrDefault(); } /// <summary> /// 创建 /// </summary> /// <param name="T"></param> /// <returns></returns> public T Create(T T) { _collection.InsertOne(T); return T; } /// <summary> /// 更新 /// </summary> /// <param name="id"></param> /// <param name="TIn"></param> public void Update(string id, T TIn) { _collection.ReplaceOne(T => T.Id == id, TIn); } /// <summary> /// 删除 /// </summary> /// <param name="TIn"></param> public void Remove(T TIn) { _collection.DeleteOne(T => T.Id == TIn.Id); } /// <summary> /// 根据id删除 /// </summary> /// <param name="id"></param> 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<Student> { public StudentService(IConfiguration config) : base(config, nameof(Student)) { } } }
配置文件 appsettings.json 加入
"ConnectionStrings": { "MongoDBDemo": "mongodb://localhost:27017" //连接字符串 }, "MongoDBSetting": { "DBName": "Test" },
上层写好后,需在Web层Startup类中配置注入service注入以便在控制中使用service操作mongodb
services.AddScoped<StudentService>(); //注入service服务
注入service后在控制器试一下好不好使,运行项目后是好使的
HomeController控制器代码:
public class HomeController : Controller { private readonly StudentService _studentService; public HomeController(StudentService studentService) //构造函数注入 { _studentService = studentService; } public IActionResult Index() { return View(); } #region CRUD /// <summary> /// 获取所有 /// </summary> /// <returns></returns> public ActionResult<List<Student>> Get() { return _studentService.Get(); } /// <summary> /// 根据id获取 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] public ActionResult<Student> Get(string id) { var Student = _studentService.Get(id); if (Student == null) { return NotFound(); } return Student; } /// <summary> ///添加 /// </summary> /// <param name="Student"></param> /// <returns></returns> public ActionResult<Student> Create(Student Student) { _studentService.Create(Student); return Ok(); } /// <summary> /// 更新 /// </summary> /// <param name="id"></param> /// <param name="StudentIn"></param> /// <returns></returns> public IActionResult Update(string id, Student StudentIn) { var Student = _studentService.Get(id); if (Student == null) { return NotFound(); } _studentService.Update(id, StudentIn); return NoContent(); } /// <summary> /// 删除 /// </summary> /// <param name="id"></param> /// <returns></returns> 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 }); } }
试一下添加删除,都是好使的: