作者:Belief | 来源:互联网 | 2023-06-15 14:46
环境:Asp.NetCoreMvc2.2,MongoDB4.09参考文档:http:mongodb.github.iomongo-csharp-driverhttp:mongodb
环境: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/
https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio
创建 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 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))
{
}
}
}
配置文件 appsettings.json 加入
"ConnectionStrings": {
"MongoDBDemo": "mongodb://localhost:27017" //连接字符串
},
"MongoDBSetting": {
"DBName": "Test"
},
上层写好后,需在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