.net core 2.2 & Mongodb
.net core 2.2 API项目中使用Mongodb 简单的CRUD封装
创建FoodPlan.Core
项目
- IEntityBase.cs
- 这个是为了方便在后面的泛型中使用id
- 这里必须要用接口 不然在创建文档约束时会报错!!
// IEntityBase.cs
using System;
namespace FoodPlan.Core.Entity
{
public interface IEntityBase
{
Guid Id { get; set; }
}
}
- Single.cs
- 测试就先写两个字段
// Single.cs
using System;
namespace FoodPlan.Core.Entity
{
public class Single: IEntityBase
{
/// <summary>
/// Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// 名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 价格
/// </summary>
public decimal Price { get; set; }
}
}
创建FoodPlan.DB项目
- 安装nuget包
- MongoDB.Driver (当前项目 V2.7.2)
- DBSettings.cs 数据库连接字符串类
- MongoContextService.cs 连接与获取文档
- IBaseRepository.cs 公共CRUD接口
- ISinglesRepository.cs Single的单独的CRUD接口
- BaseRepository.cs 公共CRUD实现
- SinglesRepository.cs Single的CRUD实现
- DBSettings.cs 数据库连接字符串类
- 这里只做最简单的连接
// DBSettings.cs
namespace FoodPlan.DB
{
/// <summary>
/// 数据连接字符串
/// </summary>
public class DBSettings
{
/// <summary>
/// 连接字符串
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// 库名称
/// </summary>
public string Database { get; set; }
}
}
- MongoContextService.cs 数据库连接字符串类
- 数据库连接
- 获取文档
- 创建文档与设置文档的字段映射与约束
- Mongodb官方约束文档(http://mongodb.github.io/mongo-csharp-driver/2.7/reference/bson/mapping/)
using Microsoft.Extensions.Options;
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.IdGenerators;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
namespace FoodPlan.DB.Mongo
{
public class MongoContextService
{
private IMongoDatabase _datebase;
//private delegate void SetBsonClassMap();
/// <summary>
/// 连接数据库
/// </summary>
/// <param name="dBSettings">.ner core 设置的链接字符串</param>
public MongoContextService(IOptions<DBSettings> dBSettings)
{
var client = new MongoClient(dBSettings.Value.ConnectionString);
if (client != null)
{
_datebase = client.GetDatabase(dBSettings.Value.Database);
}
}
/// <summary>
/// 判断文档是否存在 不存在创建
/// </summary>
/// <param name="CollectionName">文档名称</param>
/// <param name="setBsonClassMap">首次创建文档字段映射与约束设置</param>
private void CheckAndCreateCollection(string CollectionName, Action setBsonClassMap)
{
// 获取数据库中的所有文档
var collectionList = _datebase.ListCollections().ToList();
// 保存文档名称
var collectionNames = new List<string>();
// 便利获取文档名称
collectionList.ForEach(b => collectionNames.Add(b["name"].AsString));
// 判断文档是否存在
if (!collectionNames.Contains(CollectionName))
{
// 首次创建文档字段映射与约束设置
setBsonClassMap();
// 创建文档
_datebase.CreateCollection(CollectionName);
}
}
/// <summary>
/// 获取ContactSingles文档
/// </summary>
public IMongoCollection<Core.Entity.Single> ContactSingles
{
get
{
CheckAndCreateCollection("ContactSingles", SetBsonClassMapSingles);
return _datebase.GetCollection<Core.Entity.Single>("ContactSingles");
}
}
/// <summary>
/// ContactSingles文档字段映射
/// </summary>
private static void SetBsonClassMapSingles()
{
BsonClassMap.RegisterClassMap((BsonClassMap<Core.Entity.Single> cm) =>
{
cm.AutoMap();
cm.MapIdMember(x => x.Id).SetIdGenerator(CombGuidGenerator.Instance); // 使用Guid作为文档id
});
}
}
}
- IBaseRepository.cs 公共CRUD接口
- CRUD
// IBaseRepository.cs
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FoodPlan.DB.Mongo.IRepository
{
public interface IBaseRepository<T> where T: IEntityBase
{
/// <summary>
/// 添加一个数据
/// </summary>
/// <param name="addData">添加的数据</param>
/// <returns></returns>
Task AddAsync(T addData);
/// <summary>
/// 获取所有数据
/// </summary>
/// <returns></returns>
Task<IEnumerable<T>> AllAsync();
/// <summary>
/// 根据Id获取一条数据
/// </summary>
/// <param name="id">数据Guid</param>
/// <returns></returns>
Task<T> GetOneAsync(Guid id);
/// <summary>
/// 删除一条数据
/// </summary>
/// <param name="id">Guid</param>
/// <returns></returns>
Task<DeleteResult> DeleteAsync(Guid id);
/// <summary>
/// 修改一条完整的数据
/// </summary>
/// <param name="addData">修改的数据</param>
/// <returns></returns>
Task UpdateOneAsync(T addData);
}
}
- ISinglesRepository.cs Single的单独的CRUD接口
- 定义Single的单独CRUD
// ISinglesRepository.cs
namespace FoodPlan.DB.Mongo.IRepository
{
public interface ISinglesRepository: IBaseRepository<Core.Entity.Single>
{
}
}
- BaseRepository.cs 公共CRUD实现
- 注意:IOptions 是通过依赖注入到 .net core 应用时获取到的
using FoodPlan.Core.Entity;
using FoodPlan.DB.Mongo.IRepository;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace FoodPlan.DB.Mongo.Repository
{
public abstract class BaseRepository<T> : IBaseRepository<T> where T : IEntityBase
{
/// <summary>
/// 文档
/// </summary>
protected IMongoCollection<T> _context;
/// <summary>
/// 数据库
/// </summary>
protected MongoContextService _datebase;
/// <summary>
/// 构成函数
/// </summary>
/// <param name="dBSettings">数据库连接字符串</param>
///注意:IOptions 是通过依赖注入到 .net core 应用时获取到的
public BaseRepository(IOptions<DBSettings> dBSettings)
{
_datebase = new MongoContextService(dBSettings);
}
public async Task AddAsync(T data)
{
await _context.InsertOneAsync(data);
}
public async Task<IEnumerable<T>> AllAsync()
{
return await _context.Find(_ => true).ToListAsync();
}
public async Task<DeleteResult> DeleteAsync(Guid id)
{
return await _context.DeleteOneAsync(filter => filter.Id == id);
}
public async Task<T> GetOneAsync(Guid id)
{
return await _context.Find(f => f.Id == id).FirstAsync();
}
public Task UpdateOneAsync(T addData)
{
throw new NotImplementedException();
}
}
}
- SinglesRepository.cs Single的CRUD实现
using FoodPlan.DB.Mongo.IRepository;
using Microsoft.Extensions.Options;
namespace FoodPlan.DB.Mongo.Repository
{
public class SinglesRepository : BaseRepository<Core.Entity.Single>, ISinglesRepository
{
public SinglesRepository(IOptions<DBSettings> dBSettings) : base(dBSettings)
{
_context = _datebase.ContactSingles;
}
}
}
创建FoodPlan.API项目
- 修改 Program.cs
- 创建appsettings.json
- 创建appsettings.Development.json
- 创建 Startup.Development.cs
- 创建 SinglesController.cs
- 修改 Program.cs
- 环境变量设置在 Properties ->launchSettings.json
- 如果不修改Program.cs 直接使用就用任何修改了(不需要创建appsettings.Development.json)
- 环境变量设置在 Properties ->launchSettings.json
using System.Reflection;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace FoodPlan.API
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup(typeof(StartupDevelopment).GetTypeInfo().Assembly.FullName); // 根据环境变量选择启动文件
}
}
- 创建appsettings.json
- 如果你使用了 Development 环境这个就可以留空
- 如果不用 Development环境就把appsettings.Development.json的内容复制到这个文件中就可以
- 创建appsettings.Development.json
- 主要用到了连接字符串和库名称
// appsettings.Development.json
{
"MongoConnection": {
"ConnectionString": "mongodb://localhost:27017",
"Database": "Food_Plan"
}
}
- 创建 Startup.Development.cs
- 如果没有使用 Development环境 就直接写到 Startup.cs中就可以
// Startup.Development.cs
using FoodPlan.DB;
using FoodPlan.DB.Mongo.IRepository;
using FoodPlan.DB.Mongo.Repository;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace FoodPlan.API
{
public class StartupDevelopment
{
public IConfiguration Configuration { get; }
public StartupDevelopment(IConfiguration configuration)
{
Configuration = configuration;
}
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
// 获取数据库连接字符串 获取后就可以通过IOption获取对应的内容了
services.Configure<DBSettings>(options =>
{
options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoConnection:Database").Value;
});
// https设置
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 5001;
});
// 注入数据库操作
services.AddTransient<ISinglesRepository, SinglesRepository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
- 创建 SinglesController.cs
// SinglesController.cs
using System;
using System.Threading.Tasks;
using FoodPlan.DB.Mongo.IRepository;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace FoodPlan.API.Controllers
{
[Route("api/single")]
public class SinglesController : Controller
{
private readonly ISinglesRepository _singlesContext;
public SinglesController(ISinglesRepository singlesRepository)
{
_singlesContext = singlesRepository;
}
// GET: /<controller>/
[HttpGet]
public async Task<IActionResult> GetAsync()
{
return Json(await _singlesContext.AllAsync());
}
[HttpPost]
public IActionResult Post()
{
try
{
_singlesContext.AddAsync(new Core.Entity.Single() {
Name = "测试一号",
Price = 50,
});
return Ok(new { Isuccess = true });
}
catch (Exception)
{
return Ok(new { Isuccess = false });
}
}
[HttpGet("{id}")]
public async Task<IActionResult> GetOneAsync(string id)
{
return Ok(await _singlesContext.GetOneAsync(new Guid(id)));
}
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAsync(string id)
{
return Ok(await _singlesContext.DeleteAsync(new Guid(id)));
}
}
}
结束了
学习的一点笔记欢迎指教批评,有什么不妥或有什么疑问欢迎交流!!
参考了很多杨旭老师的.net core教学:
讲得非常好。
推荐大家可以看.ner core api 视频教程 https://www.bilibili.com/video/av33344382/?p=5
https://www.cnblogs.com/cgzl/p/9498482.html
https://space.bilibili.com/361469957/
.net core 2.2 & Mongodb的更多相关文章
- .NET Core也可以使用MongoDB了
可能是由于.NET Core还不是正式版的缘故吧,MongoDB的官方Driver(http://mongodb.github.io/mongo-csharp-driver/)一直不支持.NET Co ...
- 在.Net Core中使用MongoDB的入门教程(二)
在上一篇文章中,讲到了MongoDB在导入驱动.MongoDB的连接,数据的插入等. 在.Net Core中使用MongoDB的入门教程(一) 本篇文章将接着上篇文章进行介绍MongoDB在.Net ...
- 在.Net Core中使用MongoDB的入门教程(一)
首先,我们在MongoDB的官方文档中看到,MongoDb的2.4以上的For .Net的驱动是支持.Net Core 2.0的. 所以,在我们安装好了MangoDB后,就可以开始MangoDB的.N ...
- Asp.Net Core中使用MongoDB的入门教程,控制台程序使用 MongoDB
内容来源 https://blog.csdn.net/only_yu_yy/article/details/78882446 首先,创建一个.Net Core的控制台应用程序.然后使用NuGet导入 ...
- 基于.net core webapi和mongodb的日志系统
开发环境vs2017,.NET Core2.1, 数据写入到mongodb.思路就是1.提供接口写入日志,2.基于接口封装类库.3.引入类库使用 源码在最后 为什么要写它 很多开源项目像nlog.lo ...
- 在.NET Core中使用MongoDB明细教程(1):驱动基础及文档插入
MongoDB,被归类为NoSQL数据库,是一个以类JSON格式存储数据的面向文档的数据库系统.MongoDB在底层以名为bson的二进制编码格式表示JSON文档,MongoDB bson实现是轻量级 ...
- 在.NET Core中使用MongoDB明细教程(2):使用Filter语句检索文档
在上篇文章我们介绍了一些驱动程序相关的基础知识,以及如何将文档插入到集合中.在这篇文章中,我们将学习如何从数据库中检索文档. 作者:依乐祝 译文地址:https://www.cnblogs.com/y ...
- c# .net core + .net framework mongodb nuget 包
FastNet.Framework.Mongo https://github.com/my-core/FastNet.Framework GH.MongoDb.GenericRepository ht ...
- 在.NET Core中使用MongoDB明细教程(3):Skip, Sort, Limit, Projections
到目前为止,我们已经讨论了创建文档, 检索文档,现在让我们来研究一下文档排序,指定要跳过或限制返回的文档数量,以及如何进行投影.此篇文章中的实例代码摘录自原文,未像前几篇文章一样进行实际代码的验证. ...
随机推荐
- 第六篇:GPU 并行优化的几种典型策略
前言 如何对现有的程序进行并行优化,是 GPU 并行编程技术最为关注的实际问题.本文将提供几种优化的思路,为程序并行优化指明道路方向. 优化前准备 首先,要明确优化的目标 - 是要将程序提速 2 倍? ...
- jQuery之ajaxForm提交表单
1.jQuery的设计非常优雅,其源代码亦给人以美感,利用jQuery框架写出来的js既简练又能完美跨浏览器. 2.jquery form插件是基于jQuery开发的一套能够利用ajax技术提 ...
- LeetCode——Search Insert Position
Description: Given a sorted array and a target value, return the index if the target is found. If no ...
- vux组件绑定事件
我一开始是这样绑定事件的,但是没有效果: <box gap="15px 45px"> <x-button plain type="primary&quo ...
- WEB安全第六篇--千里之外奇袭客户端:XSS和HTML注入
零.前言 最近做专心web安全有一段时间了,但是目测后面的活会有些复杂,涉及到更多的中间件.底层安全.漏洞研究与安全建设等越来越复杂的东东,所以在这里想写一个系列关于web安全基础以及一些讨巧的pay ...
- 【BZOJ2141】排队 树状数组+分块
[BZOJ2141]排队 Description 排排坐,吃果果,生果甜嗦嗦,大家笑呵呵.你一个,我一个,大的分给你,小的留给我,吃完果果唱支歌,大家乐和和.红星幼儿园的小朋友们排起了长长地队伍,准备 ...
- chrome inspect 离线调试-工具包 怎么使用
1.找到相关目录: C:\Users\当前用户\AppData\Local\Google\Chrome\User Data\Default 2.找到以下文件夹: 1.Application Cache ...
- Oracle正在执行和执行过的SQL语句
1.正在执行的SQL select a.username, a.sid,b.SQL_TEXT, b.SQL_FULLTEXT from v$session a, v$sqlarea b where a ...
- C /C ++中结构体的定义
c语言中结构体的定义: struct 结构体名{ 成员列表: ..... }结构体变量: 7.1.1 结构体类型变量的定义结构体类型变量的定义与其它类型的变量的定义是一样的,但由于结构体类型需要针对问 ...
- Oracle表的维护(字段,重命名表名)
案例:银行里建的开卡信息 字段 字段类型 Id Number name Varchar2(64) sex Char2() birth Date money Number(10,2) 创建银行卡表 cr ...