Asp.Net Core MongoDB

来源:http://www.cnblogs.com/xywinnie/archive/2017/06/07/6956627.html
-Advertisement-
Play Games

廢話不說直接上代碼; using MongoDB.Bson.Serialization.Attributes; namespace XL.Core.MongoDB { public interface IEntity<TKey> { /// <summary> /// 主鍵 /// </summar ...


廢話不說直接上代碼;

using MongoDB.Bson.Serialization.Attributes;

namespace XL.Core.MongoDB
{
    public interface IEntity<TKey>
    {
        /// <summary>
        /// 主鍵
        /// </summary>
        [BsonId]
        TKey Id { get; set; }
    }
}
View Code
    [BsonIgnoreExtraElements(Inherited = true)]
    public abstract class Entity : IEntity<string>
    {
        /// <summary>
        /// 主鍵
        /// </summary>
        [BsonRepresentation(BsonType.ObjectId)]
        public virtual string Id { get; set; }
        
    }
View Code
    public interface IRepository<T, in TKey> : IQueryable<T> where T : IEntity<TKey>
    {
        #region Fileds

        /// <summary>
        /// MongoDB表
        /// </summary>
        IMongoCollection<T> DbSet { get; }

        /// <summary>
        /// MongoDB庫
        /// </summary>
        IMongoDatabase DbContext { get; }

        #endregion

        #region Find

        /// <summary>
        /// 根據主鍵獲取對象
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        T GetById(TKey id);

        /// <summary>
        /// 獲取對象
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        IEnumerable<T> Get(Expression<Func<T, bool>> predicate);

        /// <summary>
        /// 獲取對象
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = default(CancellationToken));

        #endregion

        #region Insert

        /// <summary>
        /// 插入文檔
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        T Insert(T entity);

        /// <summary>
        /// 非同步插入文檔
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task InsertAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        ///     Adds the new entities in the repository.
        /// </summary>
        /// <param name="entities">The entities of type T.</param>
        void Insert(IEnumerable<T> entities);

        /// <summary>
        /// 插入文檔
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task InsertAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default(CancellationToken));

        #endregion

        #region Update

        /// <summary>
        /// 更新文檔
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        UpdateResult Update(T entity);

        /// <summary>
        /// 非同步更新文檔
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<UpdateResult> UpdateAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));

        #endregion

        #region Delete

        /// <summary>
        /// 根據主鍵ID
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        T Delete(TKey id);

        /// <summary>
        /// 非同步根據ID刪除文檔
        /// </summary>
        /// <param name="id"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<T> DeleteAsync(TKey id, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// 非同步刪除
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<DeleteResult> DeleteAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        DeleteResult Delete(Expression<Func<T, bool>> predicate);

        #endregion

        #region Other

        /// <summary>
        /// 計數
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        long Count(Expression<Func<T, bool>> predicate);

        /// <summary>
        /// 計數
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<long> CountAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = new CancellationToken());

        /// <summary>
        /// 是否存在
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        bool Exists(Expression<Func<T, bool>> predicate);

        #endregion

        #region Query
        /// <summary>
        /// 分頁
        /// 註:只適合單屬性排序
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="sortBy"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
            int pageSize, int pageIndex = 1);
        /// <summary>
        /// 
        /// </summary>
        /// <param name="predicate"></param>
        /// <param name="sortBy"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
            int pageSize, int pageIndex = 1,
            CancellationToken cancellationToken = new CancellationToken());

        #endregion
    }

  
    public interface IRepository<T> : IRepository<T, string>
        where T : IEntity<string>
    {
    }
View Code
  public class MongoRepository<T> : IRepository<T> where T : IEntity<string>
    {
        #region Constructor

        protected MongoRepository(IMongoCollection<T> collection)
        {
            DbSet = collection;
            DbContext = collection.Database;
        }

        #endregion

        public IEnumerator<T> GetEnumerator()
        {
            return DbSet.AsQueryable().GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        #region 欄位

        public Type ElementType => DbSet.AsQueryable().ElementType;
        public Expression Expression => DbSet.AsQueryable().Expression;
        public IQueryProvider Provider => DbSet.AsQueryable().Provider;
        public IMongoCollection<T> DbSet { get; }
        public IMongoDatabase DbContext { get; }

        #endregion

        #region Find

        public T GetById(string id)
        {
            return Get(a => a.Id.Equals(id)).FirstOrDefault();
        }

        public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
        {
            return DbSet.FindSync(predicate).Current;
        }

        public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = new CancellationToken())
        {
            var task = await DbSet.FindAsync(predicate, null, cancellationToken);
            return task.Current;
        }

        #endregion

        #region Insert

        public T Insert(T entity)
        {
            DbSet.InsertOne(entity);
            return entity;
        }

        public Task InsertAsync(T entity, CancellationToken cancellationToken = new CancellationToken())
        {
            return DbSet.InsertOneAsync(entity, null, cancellationToken);
        }

        public void Insert(IEnumerable<T> entities)
        {
            DbSet.InsertMany(entities);
        }

        public Task InsertAsync(IEnumerable<T> entities, CancellationToken cancellationToken = new CancellationToken())
        {
            return DbSet.InsertManyAsync(entities, null, cancellationToken);
        }

        #endregion

        #region Update

        public UpdateResult Update(T entity)
        {
            var doc = entity.ToBsonDocument();
            return DbSet.UpdateOne(Builders<T>.Filter.Eq(e => e.Id, entity.Id),
                new BsonDocumentUpdateDefinition<T>(doc));
        }

        public Task<UpdateResult> UpdateAsync(T entity, CancellationToken cancellationToken = new CancellationToken())
        {
            var doc = entity.ToBsonDocument();
            return DbSet.UpdateOneAsync(Builders<T>.Filter.Eq(e => e.Id, entity.Id),
                new BsonDocumentUpdateDefinition<T>(doc), cancellationToken: cancellationToken);
        }

        #endregion

        #region Delete

        public T Delete(string id)
        {
            return DbSet.FindOneAndDelete(a => a.Id.Equals(id));
        }

        public Task<T> DeleteAsync(string id, CancellationToken cancellationToken = new CancellationToken())
        {
            return DbSet.FindOneAndDeleteAsync(a => a.Id.Equals(id), null, cancellationToken);
        }

        public Task<DeleteResult> DeleteAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return DbSet.DeleteManyAsync(predicate, cancellationToken);
        }

        public DeleteResult Delete(Expression<Func<T, bool>> predicate)
        {
            return DbSet.DeleteMany(predicate);
        }

        #endregion

        #region Other

        public long Count(Expression<Func<T, bool>> predicate)
        {
            return DbSet.Count(predicate);
        }

        public Task<long> CountAsync(Expression<Func<T, bool>> predicate,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return DbSet.CountAsync(predicate, null, cancellationToken);
        }

        public bool Exists(Expression<Func<T, bool>> predicate)
        {
            return Get(predicate).Any();
        }

        #endregion

        #region Page

        public IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
            int pageSize, int pageIndex = 1)
        {
            var sort = Builders<T>.Sort.Descending(sortBy);
            return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList();
        }

        public Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
            int pageSize, int pageIndex = 1,
            CancellationToken cancellationToken = new CancellationToken())
        {
            return Task.Run(() =>
            {
                var sort = Builders<T>.Sort.Descending(sortBy);
                return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList();
            }, cancellationToken);
        }

        #endregion

        #region Helper

        /// <summary>
        /// 獲取類型的所有屬性信息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TProperty"></typeparam>
        /// <param name="select"></param>
        /// <returns></returns>
        private PropertyInfo[] GetPropertyInfos<TProperty>(Expression<Func<T, TProperty>> select)
        {
            var body = select.Body;
            switch (body.NodeType)
            {
                case ExpressionType.Parameter:
                    var parameterExpression = body as ParameterExpression;
                    if (parameterExpression != null) return parameterExpression.Type.GetProperties();
                    break;
                case ExpressionType.New:
                    var newExpression = body as NewExpression;
                    if (newExpression != null)
                        return newExpression.Members.Select(m => m as PropertyInfo).ToArray();
                    break;
            }
            return null;
        }

        #endregion
    }
View Code

使用如下:

    public class MongoDBSetting
    {
        public string DataBase { get; set; }

        public string UserName { get; set; }

        public string Password { get; set; }

        public List<MongoServers> Services { get; set; }
    }

    public class MongoServers
    {
        public string Host { get; set; }

        public int Port { get; set; } = 27017;
    }
View Code

 

 public class LogsContext
    {
        private readonly IMongoDatabase _db;

        public LogsContext(IOptions<MongoDBSetting> options)

        {
            var permissionSystem =
                MongoCredential.CreateCredential(options.Value.DataBase, options.Value.UserName,
                    options.Value.Password);
            var services = new List<MongoServerAddress>();
            foreach (var item in options.Value.Services)
            {
                services.Add(new MongoServerAddress(item.Host, item.Port));
            }
            var settings = new MongoClientSettings
            {
                Credentials = new[] {permissionSystem},
                Servers = services
            };


            var _mongoClient = new MongoClient(settings);
            _db = _mongoClient.GetDatabase(options.Value.DataBase);
        }

        public IMongoCollection<ErrorLogs> ErrorLog => _db.GetCollection<ErrorLogs>("Error");

        public IMongoCollection<ErrorLogs> WarningLog => _db.GetCollection<ErrorLogs>("Warning");
    }
View Code
 public static IServiceCollection UserMongoLog(this IServiceCollection services,
            IConfigurationSection configurationSection)
        {
            services.Configure<MongoDBSetting>(configurationSection);
            services.AddSingleton<LogsContext>();
            return services;
        }
View Code
public interface IErrorLogService : IRepository<ErrorLog>
    {
    }
    public class ErrorLogService : MongoRepository<ErrorLog>, IErrorLogService
    {
        public ErrorLogService(LogsContext dbContext) : base(dbContext.ErrorLog)
        {
        }
    }
View Code

最後:

services.UserMongoLog(Configuration.GetSection("Mongo.Log"));
View Code
"Mongo.Log": {
    "DataBase": "PermissionSystem",
    "UserName": "sa",
    "Password": "shtx@123",
    "Services": [
      {
        "Host": "192.168.1.6",
        "Port": "27017"
      }
    ]
  }
View Code

剛學洗使用MongoDB,才疏學淺,請大神多多指教


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 因為項目需要在導出數據到EXECL文檔的同時還需要導出圖片進去,在處理是遇到的一些問題,在此記錄一下。 首先代碼寫好之後放測試伺服器上去執行的時候報錯了,報檢索 COM 類工廠中 CLSID 為 {00024500-0000-0000-C000-000000000046} 的組件時失敗,原因是出現以 ...
  • 由於谷歌翻譯官方API是付費版本,本著免費和開源的精神,分享一下用C#實現谷歌翻譯API的代碼。這個代碼非常簡單,主要分兩塊:通過WebRequest的方式請求內容;獲取Get方式的請求參數(難點在於tk的獲取)。 一、WebRequest代碼 二、谷歌翻譯介面的實現 1、抓包查看翻譯網路請求,這裡 ...
  • 在之前介紹的附件管理模塊裡面《Winform開發框架之通用附件管理模塊》以及《Winform開發框架之附件管理應用》,介紹了附件的管理功能,通過對資料庫記錄的處理和文件的管理,實現了附件文件和記錄的整合管理,可以運用在單機版的WInform框架,也可以使用在分散式的混合式開發框架中,隨著一些開發場景... ...
  • 其實要實現返回上一頁的功能,主要還是要用到JavaScript。 一: 在ASP.net的aspx裡面的源代碼中 <input type="button onclick="Javascript:window.history.go(-1);"value="返回上一頁"> 淺析:這個是用了HTML控制項, ...
  • 每次同步或者上傳代碼到githun上的代碼庫時,需要每次都輸入用戶名和密碼,這時我們設置一下SSH key就可以省去這些麻煩了。若果使用TortoiseGit作為github本地管理工具,TortoiseGit使用擴展名為ppk的秘鑰,而不是ssh-keygen生成的rsa密鑰。也就是說使用ssh- ...
  • 本人系初學菜鳥,如有大神路過望指點一二,小弟不勝感激!!! 1。配置hosts文件 (路徑:C:\Windows\System32\drivers\etc) 2.IIS管理器添加網站 3.修改預設文檔 4.用管理員打開vs。右鍵項目站點 設置屬性 ...
  • 題目:做一個商場收銀的小程式,可能會出現的情況包括:正常收費,九折優惠,七折優惠,滿300減50等各種不同隨時會變化的優惠活動。 界面如下: 分析: 首先我們對於收錢寫一個父類CashSuper。這個父類是用來包含其他的各種收費方式的:正常收費、七折優惠、八折優惠、九折優惠、滿300減50、滿400 ...
  • 先定義枚舉 上面這個方法根據傳入的枚舉值通過反射獲得display中name的值 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...