話不多說直接上代碼 連接字元串: 主體代碼: IMongoModel: 值得註意的是:需引用MongoDB.BSon與MongoDB.Driver VS2017若在引用包後,還是無法找到命名空間,重啟VS即可。 ABCDEFG.GetAppSetting("mongodb"));讀取配置文件 ...
話不多說直接上代碼
連接字元串:
{ "AppSettings": { "mongodb": "mongodb://用戶名:密碼@IP地址:埠號" } }
主體代碼:
1 using ABCDEFG.Config; 2 using MongoDB.Driver; 3 using System; 4 using System.Collections.Generic; 5 using System.Linq.Expressions; 6 using System.Text; 7 8 namespace Mongodb 9 { 10 public class MongoContext 11 { 12 public MongoContext() 13 { 14 Client = new MongoClient(ABCDEFG..GetAppSetting("mongodb")); 15 } 16 17 public MongoContext(string connectionName) 18 { 19 Client = new MongoClient(MengTConfig.GetAppSetting(connectionName)); 20 } 21 22 private MongoClient Client { get; set; } 23 24 private IMongoDatabase DataBase { get => Client.GetDatabase("MengTLog"); } 25 26 public IMongoCollection<T> DbSet<T>() where T : IMongoModel => DataBase.GetCollection<T>("MengTLog.Logger"); 27 28 } 29 30 public static class MongoExtend 31 { 32 public static void Add<T>(this IMongoCollection<T> collenction, T Model) where T : IMongoModel 33 => collenction.InsertOne(Model); 34 35 public static void AddList<T>(this IMongoCollection<T> collenction, List<T> Model) where T : IMongoModel 36 => collenction.InsertMany(Model); 37 38 /// <summary> 39 /// 查找第一個 40 /// </summary> 41 public static T FirstOrDefault<T>(this IMongoCollection<T> collenction,Expression<Func<T, bool>> expression) where T : IMongoModel 42 { 43 if (expression == null) { throw new ArgumentNullException("參數無效"); } 44 return collenction.Find(expression).FirstOrDefault(); 45 } 46 47 /// <summary> 48 /// 查找符合數據列表 49 /// </summary> 50 public static List<T> FindToList<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IMongoModel 51 { 52 if (expression == null) { throw new ArgumentNullException("參數無效"); } 53 return collenction.Find(expression).ToList(); 54 } 55 56 /// <summary> 57 /// 刪除全部匹配數據 58 /// </summary> 59 public static void Delete<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IMongoModel 60 { 61 if (expression == null) { throw new ArgumentNullException("參數無效"); } 62 collenction.DeleteManyAsync(expression); 63 } 64 65 66 /// <summary> 67 /// 刪除一個 68 /// </summary> 69 public static void DeleteOne<T>(this IMongoCollection<T> collenction, Expression<Func<T, bool>> expression) where T : IMongoModel 70 { 71 if (expression == null) { throw new ArgumentNullException("參數無效"); } 72 collenction.DeleteOneAsync(expression); 73 } 74 } 75 }
IMongoModel:
1 using MongoDB.Bson; 2 using System; 3 using System.Collections.Generic; 4 using System.Text; 5 6 namespace Mongodb 7 { 8 public partial class IMongoModel 9 { 10 /// <summary> 11 /// 基礎ID 12 /// </summary> 13 public ObjectId _id { get; set; } 14 } 15 }
值得註意的是:需引用MongoDB.BSon與MongoDB.Driver
VS2017若在引用包後,還是無法找到命名空間,重啟VS即可。
ABCDEFG.GetAppSetting("mongodb"));讀取配置文件