.net core 2.2 & Mongodb

.net core 2.2 API項目中使用Mongodb 簡單的CRUD封裝

項目結(jié)構(gòu)

創(chuàng)建FoodPlan.Core項目

  • 創(chuàng)建IEntityBase.cs 接口約束
  • 創(chuàng)建Single.cs 實體

  • IEntityBase.cs
    • 這個是為了方便在后面的泛型中使用id
    • 這里必須要用接口 不然在創(chuàng)建文檔約束時會報錯!!
// 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; }
    }
}


創(chuàng)建FoodPlan.DB項目

  • 安裝nuget包
    • MongoDB.Driver (當(dāng)前項目 V2.7.2)
  • DBSettings.cs 數(shù)據(jù)庫連接字符串類
  • MongoContextService.cs 連接與獲取文檔
  • IBaseRepository.cs 公共CRUD接口
  • ISinglesRepository.cs Single的單獨的CRUD接口
  • BaseRepository.cs 公共CRUD實現(xiàn)
  • SinglesRepository.cs Single的CRUD實現(xiàn)

  • DBSettings.cs 數(shù)據(jù)庫連接字符串類
    • 這里只做最簡單的連接
// DBSettings.cs
namespace FoodPlan.DB
{
    /// <summary>
    /// 數(shù)據(jù)連接字符串
    /// </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>
        /// 連接數(shù)據(jù)庫
        /// </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ù)庫中的所有文檔
            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>
        /// 添加一個數(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的單獨的CRUD接口
    • 定義Single的單獨CRUD
// ISinglesRepository.cs
namespace FoodPlan.DB.Mongo.IRepository
{
    public interface ISinglesRepository: IBaseRepository<Core.Entity.Single>
    {
    }
}
  • BaseRepository.cs 公共CRUD實現(xiàn)
    • 注意:IOptions 是通過依賴注入到 .net core 應(yīng)用時獲取到的
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ù)庫
        /// </summary>
        protected MongoContextService _datebase;
        /// <summary>
        /// 構(gòu)成函數(shù)
        /// </summary>
        /// <param name="dBSettings">數(shù)據(jù)庫連接字符串</param>
        ///注意:IOptions 是通過依賴注入到 .net core 應(yīng)用時獲取到的
        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實現(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項目

  • 修改 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 直接使用就用任何修改了(不需要創(chuàng)建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); // 根據(jù)環(huán)境變量選擇啟動文件
    }
}

  • 創(chuàng)建appsettings.json

    • 如果你使用了 Development 環(huán)境這個就可以留空
    • 如果不用 Development環(huán)境就把appsettings.Development.json的內(nèi)容復(fù)制到這個文件中就可以
  • 創(chuàng)建appsettings.Development.json

    • 主要用到了連接字符串和庫名稱
// appsettings.Development.json
{
  "MongoConnection": {
    "ConnectionString": "mongodb://localhost:27017",
    "Database": "Food_Plan"
  }
}
  • 創(chuàng)建 Startup.Development.cs
    • 如果沒有使用 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ù)庫連接字符串 獲取后就可以通過IOption獲取對應(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ù)庫操作
            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 = "測試一號",
                    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í)的一點筆記歡迎指教批評,有什么不妥或有什么疑問歡迎交流!!
參考了很多楊旭老師的.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/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,501評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,673評論 3 429
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,610評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,939評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 72,668評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,004評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,001評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 43,173評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,705評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 41,426評論 3 359
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,656評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,139評論 5 364
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,833評論 3 350
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,247評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,580評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,371評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 48,621評論 2 380

推薦閱讀更多精彩內(nèi)容