.net core 2.2 API項(xiàng)目中使用Mongodb 簡(jiǎn)單的CRUD封裝
創(chuàng)建FoodPlan.Core項(xiàng)目
- 創(chuàng)建IEntityBase.cs 接口約束
- 創(chuàng)建Single.cs 實(shí)體
- IEntityBase.cs
- 這個(gè)是為了方便在后面的泛型中使用id
- 這里必須要用接口 不然在創(chuàng)建文檔約束時(shí)會(huì)報(bào)錯(cuò)!!
// IEntityBase.cs
using System;
namespace FoodPlan.Core.Entity
{
public interface IEntityBase
{
Guid Id { get; set; }
}
}
- Single.cs
- 測(cè)試就先寫兩個(gè)字段
// 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>
/// 價(jià)格
/// </summary>
public decimal Price { get; set; }
}
}
創(chuàng)建FoodPlan.DB項(xiàng)目
- 安裝nuget包
- MongoDB.Driver (當(dāng)前項(xiàng)目 V2.7.2)
- DBSettings.cs 數(shù)據(jù)庫(kù)連接字符串類
- MongoContextService.cs 連接與獲取文檔
- IBaseRepository.cs 公共CRUD接口
- ISinglesRepository.cs Single的單獨(dú)的CRUD接口
- BaseRepository.cs 公共CRUD實(shí)現(xiàn)
- SinglesRepository.cs Single的CRUD實(shí)現(xiàn)
- DBSettings.cs 數(shù)據(jù)庫(kù)連接字符串類
- 這里只做最簡(jiǎn)單的連接
// DBSettings.cs
namespace FoodPlan.DB
{
/// <summary>
/// 數(shù)據(jù)連接字符串
/// </summary>
public class DBSettings
{
/// <summary>
/// 連接字符串
/// </summary>
public string ConnectionString { get; set; }
/// <summary>
/// 庫(kù)名稱
/// </summary>
public string Database { get; set; }
}
}
- MongoContextService.cs 數(shù)據(jù)庫(kù)連接字符串類
- 數(shù)據(jù)庫(kù)連接
- 獲取文檔
- 創(chuàng)建文檔與設(shè)置文檔的字段映射與約束
- 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>
/// 連接數(shù)據(jù)庫(kù)
/// </summary>
/// <param name="dBSettings">.ner core 設(shè)置的鏈接字符串</param>
public MongoContextService(IOptions<DBSettings> dBSettings)
{
var client = new MongoClient(dBSettings.Value.ConnectionString);
if (client != null)
{
_datebase = client.GetDatabase(dBSettings.Value.Database);
}
}
/// <summary>
/// 判斷文檔是否存在 不存在創(chuàng)建
/// </summary>
/// <param name="CollectionName">文檔名稱</param>
/// <param name="setBsonClassMap">首次創(chuàng)建文檔字段映射與約束設(shè)置</param>
private void CheckAndCreateCollection(string CollectionName, Action setBsonClassMap)
{
// 獲取數(shù)據(jù)庫(kù)中的所有文檔
var collectionList = _datebase.ListCollections().ToList();
// 保存文檔名稱
var collectionNames = new List<string>();
// 便利獲取文檔名稱
collectionList.ForEach(b => collectionNames.Add(b["name"].AsString));
// 判斷文檔是否存在
if (!collectionNames.Contains(CollectionName))
{
// 首次創(chuàng)建文檔字段映射與約束設(shè)置
setBsonClassMap();
// 創(chuàng)建文檔
_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>
/// 添加一個(gè)數(shù)據(jù)
/// </summary>
/// <param name="addData">添加的數(shù)據(jù)</param>
/// <returns></returns>
Task AddAsync(T addData);
/// <summary>
/// 獲取所有數(shù)據(jù)
/// </summary>
/// <returns></returns>
Task<IEnumerable<T>> AllAsync();
/// <summary>
/// 根據(jù)Id獲取一條數(shù)據(jù)
/// </summary>
/// <param name="id">數(shù)據(jù)Guid</param>
/// <returns></returns>
Task<T> GetOneAsync(Guid id);
/// <summary>
/// 刪除一條數(shù)據(jù)
/// </summary>
/// <param name="id">Guid</param>
/// <returns></returns>
Task<DeleteResult> DeleteAsync(Guid id);
/// <summary>
/// 修改一條完整的數(shù)據(jù)
/// </summary>
/// <param name="addData">修改的數(shù)據(jù)</param>
/// <returns></returns>
Task UpdateOneAsync(T addData);
}
}
- ISinglesRepository.cs Single的單獨(dú)的CRUD接口
- 定義Single的單獨(dú)CRUD
// ISinglesRepository.cs
namespace FoodPlan.DB.Mongo.IRepository
{
public interface ISinglesRepository: IBaseRepository<Core.Entity.Single>
{
}
}
- BaseRepository.cs 公共CRUD實(shí)現(xiàn)
- 注意:IOptions 是通過(guò)依賴注入到 .net core 應(yīng)用時(shí)獲取到的
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>
/// 數(shù)據(jù)庫(kù)
/// </summary>
protected MongoContextService _datebase;
/// <summary>
/// 構(gòu)成函數(shù)
/// </summary>
/// <param name="dBSettings">數(shù)據(jù)庫(kù)連接字符串</param>
///注意:IOptions 是通過(guò)依賴注入到 .net core 應(yīng)用時(shí)獲取到的
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實(shí)現(xiàn)
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;
}
}
}
創(chuàng)建FoodPlan.API項(xiàng)目
- 修改 Program.cs
- 創(chuàng)建appsettings.json
- 創(chuàng)建appsettings.Development.json
- 創(chuàng)建 Startup.Development.cs
- 創(chuàng)建 SinglesController.cs
- 修改 Program.cs
-
環(huán)境變量設(shè)置在 Properties ->launchSettings.json
- 如果不修改Program.cs 直接使用就用任何修改了(不需要?jiǎng)?chuàng)建appsettings.Development.json)
-
環(huán)境變量設(shè)置在 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); // 根據(jù)環(huán)境變量選擇啟動(dòng)文件
}
}
-
創(chuàng)建appsettings.json
- 如果你使用了 Development 環(huán)境這個(gè)就可以留空
- 如果不用 Development環(huán)境就把a(bǔ)ppsettings.Development.json的內(nèi)容復(fù)制到這個(gè)文件中就可以
-
創(chuàng)建appsettings.Development.json
- 主要用到了連接字符串和庫(kù)名稱
// appsettings.Development.json
{
"MongoConnection": {
"ConnectionString": "mongodb://localhost:27017",
"Database": "Food_Plan"
}
}
- 創(chuàng)建 Startup.Development.cs
- 如果沒(méi)有使用 Development環(huán)境 就直接寫到 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();
// 獲取數(shù)據(jù)庫(kù)連接字符串 獲取后就可以通過(guò)IOption獲取對(duì)應(yīng)的內(nèi)容了
services.Configure<DBSettings>(options =>
{
options.ConnectionString = Configuration.GetSection("MongoConnection:ConnectionString").Value;
options.Database = Configuration.GetSection("MongoConnection:Database").Value;
});
// https設(shè)置
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 5001;
});
// 注入數(shù)據(jù)庫(kù)操作
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();
}
}
}
- 創(chuàng)建 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 = "測(cè)試一號(hào)",
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)));
}
}
}
結(jié)束了
學(xué)習(xí)的一點(diǎn)筆記歡迎指教批評(píng)瓣铣,有什么不妥或有什么疑問(wèn)歡迎交流N赶摹扑眉!
參考了很多楊旭老師的.net core教學(xué):
講得非常好昼捍。
推薦大家可以看.ner core api 視頻教程 https://www.bilibili.com/video/av33344382/?p=5
https://www.cnblogs.com/cgzl/p/9498482.html
https://space.bilibili.com/361469957/