.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/