ASP.NET Core使用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/
创建 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 = , Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
试一下添加删除,都是好使的:


ASP.NET Core使用MongoDB数据库的更多相关文章
- asp.net core集成MongoDB
0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...
- Asp.Net Core Use MongoDB
前几天在网上想找一下Asp.Net Core使用MongoDB相关的文章,也看了几篇,发现都是在写简单的例子,这样的例子是不能用在生产环境的,不能用的生产环境的.封装一个东西一定是建立在你对这个东西足 ...
- ASP.NET Core Identity自定义数据库结构和完全使用Dapper而非EntityFramework Core
前言 原本本节内容是不存在的,出于有几个人问到了我:我想使用ASP.NET Core Identity,但是我又不想使用默认生成的数据库表,想自定义一套,我想要使用ASP.NE Core Identi ...
- Asp.Net Core 使用 Sqlite 数据库
在Asp.Net Core 使用 Sqlite 数据库 在Asp.Net Core(5.0)项目中使用Sqlite数据库的设置, 1,创建新web项目 2,安装下面的依赖包 Install-Packa ...
- Asp.Net Core链接Mysql数据库
一.新建一个Asp.Net Core WebMVC程序 添加nuget包 Mysql.Data 二.新建一个UserContext类 下面代码中的UserInfo是我自己建的一个实体,里面有俩字段: ...
- (18)ASP.NET Core 基于现有数据库创建EF模型(反向工程)
1.简介 Entity Framework Core可通过数据库提供给应用程序的插件访问许多不同的数据库.我们可以通过使用Entity Framework Core构建执行基本数据访问的ASP.NET ...
- Asp.Net Core Identity 多数据库支持
Asp.Net Core Identity 是.Net自带的身份认证系统,支持用户界面 (UI) 登录功能,并且管理用户.密码.配置文件数据.角色.声明.令牌.电子邮件确认等等.使用Visual St ...
- Asp.Net Core使用MongoDB
MongoDB 是一个基于分布式且面向文档存储的开源 NoSql数据库系统 MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.它支持的数据结构 ...
- Asp.Net Core如何根据数据库自动生成实体类
通过引用Nuget包添加实体类 运行 Install-Package Microsoft.EntityFrameworkCore.SqlServer 运行 Install-Package Micros ...
随机推荐
- 001-k8s集群的安装
k8s集群的安装 1.实验描述 通过搭建 K8S 的集群,来学习对容器的编排 2.实验环境 [你可能需要][CentOS 7 搭建模板机]点我快速打开文章 [你可能需要][VMware 从模板机快速克 ...
- BCD解密
#include<stdio.h> int main(void) { int num; scanf_s("%d", &num); printf( * + num ...
- Google开源PDF软件库
Google开启了一个叫做PDFium的PDF软件库开源项目,开发人员能够将其纳入各种平台应用中. 据Google的Chromium项目的布道师François Beaufort称,PDFium将被包 ...
- 【oracle】 months_between(date1,date2)
(20090228,20080228)====12 (20090228,20080229)====12 (20080229,20070228)====12 (20100331,20100228)=== ...
- mysql悲观锁的实现
https://www.cnblogs.com/laoyeye/p/8228467.html 参考原文链接, //0.开始事务 begin;/begin work;/start transaction ...
- chrome 模拟发送请求的方法
chrome f12 看到了web页面的请求,有时候想修改一下参数重新执行一下怎么办? 如果是get方法.参数不多可以直接在浏览器中打开.否则post方法参数多时很多人会复制到postman中执行,但 ...
- [LeetCode] 464. Can I Win 我能赢吗
In the "100 game," two players take turns adding, to a running total, any integer from 1.. ...
- [LeetCode] 119. Pascal's Triangle II 杨辉三角之二
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note t ...
- [LeetCode] 103. Binary Tree Zigzag Level Order Traversal 二叉树的之字形层序遍历
Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to ...
- 原生/CM系列网络叹号问题
网络叹号问题: 原因:某墙屏蔽了谷歌,而原生安卓是利用谷歌的服务器来测试网络是否通畅的 解决方案:修改网络测试的服务器地址 方案来源:https://www.noisyfox.io/android-c ...
