.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项目


  • 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; }
}
}
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

    • 环境变量设置在 Properties ->launchSettings.json

    • 如果不修改Program.cs 直接使用就用任何修改了(不需要创建appsettings.Development.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的更多相关文章

  1. .NET Core也可以使用MongoDB了

    可能是由于.NET Core还不是正式版的缘故吧,MongoDB的官方Driver(http://mongodb.github.io/mongo-csharp-driver/)一直不支持.NET Co ...

  2. 在.Net Core中使用MongoDB的入门教程(二)

    在上一篇文章中,讲到了MongoDB在导入驱动.MongoDB的连接,数据的插入等. 在.Net Core中使用MongoDB的入门教程(一) 本篇文章将接着上篇文章进行介绍MongoDB在.Net ...

  3. 在.Net Core中使用MongoDB的入门教程(一)

    首先,我们在MongoDB的官方文档中看到,MongoDb的2.4以上的For .Net的驱动是支持.Net Core 2.0的. 所以,在我们安装好了MangoDB后,就可以开始MangoDB的.N ...

  4. Asp.Net Core中使用MongoDB的入门教程,控制台程序使用 MongoDB

    内容来源  https://blog.csdn.net/only_yu_yy/article/details/78882446 首先,创建一个.Net Core的控制台应用程序.然后使用NuGet导入 ...

  5. 基于.net core webapi和mongodb的日志系统

    开发环境vs2017,.NET Core2.1, 数据写入到mongodb.思路就是1.提供接口写入日志,2.基于接口封装类库.3.引入类库使用 源码在最后 为什么要写它 很多开源项目像nlog.lo ...

  6. 在.NET Core中使用MongoDB明细教程(1):驱动基础及文档插入

    MongoDB,被归类为NoSQL数据库,是一个以类JSON格式存储数据的面向文档的数据库系统.MongoDB在底层以名为bson的二进制编码格式表示JSON文档,MongoDB bson实现是轻量级 ...

  7. 在.NET Core中使用MongoDB明细教程(2):使用Filter语句检索文档

    在上篇文章我们介绍了一些驱动程序相关的基础知识,以及如何将文档插入到集合中.在这篇文章中,我们将学习如何从数据库中检索文档. 作者:依乐祝 译文地址:https://www.cnblogs.com/y ...

  8. c# .net core + .net framework mongodb nuget 包

    FastNet.Framework.Mongo https://github.com/my-core/FastNet.Framework GH.MongoDb.GenericRepository ht ...

  9. 在.NET Core中使用MongoDB明细教程(3):Skip, Sort, Limit, Projections

    到目前为止,我们已经讨论了创建文档, 检索文档,现在让我们来研究一下文档排序,指定要跳过或限制返回的文档数量,以及如何进行投影.此篇文章中的实例代码摘录自原文,未像前几篇文章一样进行实际代码的验证. ...

随机推荐

  1. 如何快速入门单片机C语言

    一.为什么要学单片机技术? 传统的电子产品升级改造成智能化的电子产品需要用到单片机技术.也就是说传统的电子产品如电视机.电子表.计算器.数码相机.手机.MP3.遥控器.洗衣机等产品智能化.微型化,需要 ...

  2. Apache nutch1.5 & Apache solr3.6

    第1章引言 1.1nutch和solr Nutch 是一个开源的.Java 实现的搜索引擎.它提供了我们运行自己的搜索引擎所需的全部工具. Solr 拥有像 web-services API 的独立的 ...

  3. 控制input框的内容输入为数字

    <script> function toNum(v) { return v.replace(/[^\d.]/g, '').replace(/^\./g, "").rep ...

  4. [Web Chart系列之六] canvas Chart 导出图文件

    前言 博主正在参加CSDN2013年度博客之星评选,如果这篇文章对您有用,请投他一票: 投票地址:http://vote.blog.csdn.net/blogstaritem/blogstar2013 ...

  5. LeetCode——Move Zeroes

    Description: Given an array nums, write a function to move all 0's to the end of it while maintainin ...

  6. PHP 允许Ajax跨域访问 (Access-Control-Allow-Origin)

    Ajax访问php,报错 php顶部加上即可: header("Access-Control-Allow-Origin: *");

  7. IOS中使用轻量级数据库

    IOS中使用轻量级数据库 目录 概述 IOS中的轻量级数据库 sqlite的方法 数据库的实用操作 第三方类库 FMDatabase 概述 IOS中的轻量级数据库 sqlite的方法 sqlite3 ...

  8. 【BZOJ2434】[NOI2011]阿狸的打字机 AC自动机+DFS序+树状数组

    [BZOJ2434][NOI2011]阿狸的打字机 Description 阿狸喜欢收藏各种稀奇古怪的东西,最近他淘到一台老式的打字机.打字机上只有28个按键,分别印有26个小写英文字母和'B'.'P ...

  9. HTML5+CSS3 表格设计(Table)

    <style> body { width: 600px; margin: 40px auto; font-family: 'trebuchet MS', 'Lucida sans', Ar ...

  10. ios ASIHTTPRequest类库简介和使用说明

    官方网站: http://allseeing-i.com/ASIHTTPRequest/ .可以从上面下载到最新源码,以及获取到相关的资料. 使用iOS SDK中的HTTP网络请求API,相当的复杂, ...