你的位置:首页 > ASP.net教程

[ASP.net教程]c# 用mongodb官方driver写的一些蛋疼的封装类


  其实我真的很讨厌用.net,尤其是自从接触了nodejs,go之后,就更讨厌用.net了。不过公司还是非要用,而且写了这么个接口,这个也不算什么代码产权,所以放出来,大家看看用得着的就拿走,写的不好的帮我改改,我也能提高提高。

  一共就两个类一个接口,接口我就不放了,两个类中的代码我放出一些,然后调用Demo放一下。

  这个是那个处理类

 1 public partial class MongoHelperFromEntity<T>: IMongoHelper<T> 2   { 3     #region variable 4     IMongoClient mongoClient = null; 5     IMongoCollection<T> collection = null; 6     IMongoDatabase db; 7     string connString = string.Empty; 8     string connDB = string.Empty; 9     #endregion 10     public MongoHelperFromEntity(string collectionname) 11     { 12       #region check webconfig 13       try 14       { 15         connString = ConfigurationManager.AppSettings["mongodbConnection"]; 16       } 17       catch (Exception) 18       { 19         throw new Exception("plese add mongodbConnection in webconfig"); 20       } 21       try 22       { 23         connDB = ConfigurationManager.AppSettings["mongodbDatabase"]; 24       } 25       catch (Exception) 26       { 27         throw new Exception("plese add mongodbDatabase in webconfig"); 28       } 29       #endregion  30       if (mongoClient == null) 31       { 32         mongoClient = new MongoClient(connString); 33         db = mongoClient.GetDatabase(connDB); 34         collection = db.GetCollection<T>(collectionname); 35       } 36     } 37     #region fun 38     private async Task<string> _Insert(T entity) 39     { 40  41       string flag = null; 42       try 43       { 44         flag = ObjectId.GenerateNewId().ToString(); 45         entity.GetType().GetProperty("_id").SetValue(entity, flag); 46         await collection.InsertOneAsync(entity); 47       } 48       catch (Exception)  49       { 50          51       } 52       return flag; 53     } 54     Task<UpdateResult> _Push(string id, Expression<Func<T, IEnumerable<object>>> filed, object value) 55     { 56       Task<UpdateResult> flag = null; 57       try 58       { 59         FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id); 60         flag = collection.UpdateOneAsync(filter, MongoDB.Driver.Builders<T>.Update.Push(filed, value)); 61       } 62       catch (Exception){} 63       return flag; 64     } 65     Task<UpdateResult> _Pull<C>(string id, Expression<Func<T, IEnumerable<C>>> filed, Expression<Func<C, bool>> expression) 66     { 67       Task<UpdateResult> flag = null; 68       try 69       { 70         FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id); 71         flag = collection.UpdateOneAsync(filter, MongoDB.Driver.Builders<T>.Update.PullFilter(filed,expression)); 72       } 73       catch (Exception) { } 74       return flag; 75     } 76     Task<List<T>> _Find(string[] fields, Dictionary<string, int> sortfields, System.Linq.Expressions.Expression<Func<T, bool>> expression) 77     { 78       IFindFluent<T, T> iff = null; 79       if (expression == null) 80       { 81         iff = collection.Find<T>(new BsonDocument()); 82       } 83       else 84       { 85         iff = collection.Find<T>(expression); 86       } 87       if (fields.Length > 0) 88       { 89         Dictionary<string,int> dicfields = new Dictionary<string,int>(); 90         foreach (string item in fields) 91         { 92           dicfields.Add(item,1); 93         } 94         iff = iff.Project<T>(Tools<T>.getDisplayFiles(dicfields)); 95       } 96       if(sortfields != null) 97       { 98         iff = iff.Sort(Tools<T>.getSortDefinition(sortfields)); 99       }100       return iff.ToListAsync();101     }102     Task<T> _FindOne(string id,string[] fields)103     {104       Task<T> result = null;105       IFindFluent<T, T> iff = null;106       try107       {108         FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);109         iff = collection.Find<T>(filter);110         if (fields!= null && fields.Length > 0)111         {112           Dictionary<string, int> dicfields = new Dictionary<string, int>();113           foreach (string item in fields)114           {115             dicfields.Add(item, 1);116           }117           iff = iff.Project<T>(Tools<T>.getDisplayFiles(dicfields));118         }119         result = iff.FirstOrDefaultAsync();120       }121       catch (Exception)122       {123       }124       return result;125 126     }127     Task<ReplaceOneResult> _Replace(string id , object data)128     {129       Task<ReplaceOneResult> result = null;130       try131       {132         FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);133         data.GetType().GetProperty("_id").SetValue(data, id);134         result = collection.ReplaceOneAsync(filter, (T)data);135       }136       catch (Exception)137       {138       }139       return result;140     }141     Task<UpdateResult> _Update(string id,Dictionary<string,object> updatedic)142     {143       Task<UpdateResult> result = null;144       if (updatedic.Count > 0)145       {146         try147         {148           FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);149           result = collection.UpdateOneAsync(filter, Tools<T>.getUpdateDefinition(updatedic));150         }151         catch (Exception)152         {153         }154         155       }156       return result;157     }158     Task<DeleteResult> _Delete(string id)159     {160       Task<DeleteResult> result = null;161       try162       {163         FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);164         result =collection.DeleteOneAsync(filter);165       }166       catch (Exception)167       {168         169       }170       return result;171     }172     #endregion173   }

View Code

  这个是一个工具类,我本来想放一些公用的东西,但是貌似没提出多少

 1   public static class Tools<T> 2   { 3     public static FieldsDocument getDisplayFiles(Dictionary<string, int> fields) 4     { 5       FieldsDocument fd = new FieldsDocument(); 6       fd.AddRange(fields); 7       return fd; 8     } 9     public static SortDefinition<T> getSortDefinition(Dictionary<string,int> sortfields)10     {11       SortDefinition<T> sd = null;12       foreach (var item in sortfields)13       {14         if (sd == null)15         {16           if (item.Value == 1)17           {18             sd = Builders<T>.Sort.Ascending(item.Key);19           }20           else21           {22             sd = Builders<T>.Sort.Descending(item.Key);23           }24         }25         else26         {27           if (item.Value == 1)28           {29             sd.Ascending(item.Key);30           }31           else32           {33             sd.Descending(item.Key);34           }35         }36       }37       return sd;38     }39     public static UpdateDefinition<T> getUpdateDefinition(Dictionary<string, object> updatedic)40     {41       UpdateDefinition<T> ud = null;42       foreach (var item in updatedic)43       {44         if (ud == null)45         {46           ud = Builders<T>.Update.Set(item.Key, item.Value);47         }48         else49         {50           ud.Set(item.Key, item.Value);51         }52       }53       return ud;54     }55   }

View Code

  然后这里是一些调用的demo,当然是调用接口,大家要用的时候自己写一个接口类然后调用或者直接实例化调用就好了。

 1 IMongoHelper<Document> imh; 2     protected void Page_Load(object sender, EventArgs e) 3     { 4       imh = new MongoHelperFromEntity<Document>("Documents"); 5       #region Insert 6       for (int i = 1; i < 11; i++) 7       { 8         if (imh.Insert(new Document("document" + i.ToString())) == null) 9         { 10           Response.Write("<script>alert('err')</script>"); 11           break; 12         } 13       } 14       Response.Write("<script>alert('ok')</script>"); 15       #endregion 16       #region Push 17       if (imh.Push("568231e7d6f684683c253f6a", d => d.Comment, new Comment("CN002", "Hi"))) 18       { 19         Response.Write("<script>alert('ok')</script>"); 20       } 21       else 22       { 23         Response.Write("<script>alert('err')</script>"); 24       } 25       #endregion 26       #region Pull 27       if (imh.Pull<Comment>("568231e7d6f684683c253f6a", d => d.Comment, c => c.StaffID == "CN001")) 28       { 29         Response.Write("<script>alert('ok')</script>"); 30       } 31       else 32       { 33         Response.Write("<script>alert('err')</script>"); 34       } 35       #endregion 36       #region FindOne 37       Document doc = imh.FindOne("56822480d6f68424c8db56f2").Result; 38       #endregion 39       #region Find 40       string[] fields = { "Title" }; 41       Dictionary<string, int> dicfields = new Dictionary<string, int>(); 42       dicfields.Add("Time", 0); 43       List<Document> uu = imh.Find(fields, dicfields, u => u._id == "568231e7d6f684683c253f73").Result; 44       #endregion 45       #region Replace 46       if (imh.Replace("568231e7d6f684683c253f6a", new Document("document_replace"))) 47       { 48         Response.Write("<script>alert('ok')</script>"); 49       } 50       else 51       { 52         Response.Write("<script>alert('err')</script>"); 53       } 54       #endregion 55       #region Update 56       Dictionary<string, object> dic = new Dictionary<string, object>(); 57       dic.Add("Title", "document_update"); 58       dic.Add("Time", DateTime.Now); 59       if (imh.Update("568231e7d6f684683c253f73", dic)) 60       { 61         Response.Write("<script>alert('ok')</script>"); 62       } 63       else 64       { 65         Response.Write("<script>alert('err')</script>"); 66       } 67       #endregion 68       #region Delete 69       if (imh.Delete("568231e7d6f684683c253f73")) 70       { 71         Response.Write("<script>alert('ok')</script>"); 72       } 73       else 74       { 75         Response.Write("<script>alert('err')</script>"); 76       } 77       #endregion 78       //要注意的地方 79       //1.是lambda准确 80  81       //2.在构造对象时,如果这个对象是一个collection中的document时,一定要添加属性"_id",例如Model中Document中所示,在Insert时,_id不用赋值,后台会赋值,但是所用名称一定按照如下所示 82       //private object id; 83       //public object _id 84       //{ 85       //  get { return id; } 86       //  set { id = value; } 87       //} 88  89       //3.当对象中有List行属性时一定要付初值例如Model中Document中所示 90       //private List<Comment> _Comment ; 91       //public List<Comment> Comment 92       //{ 93       //  get { 94       //    if (_Comment == null) { _Comment = new List<Comment>(); } 95       //    return _Comment;  96       //  } 97       //  set { _Comment = value; } 98       //} 99 100       //4.Pull操作中后面的对象为要插入到List中的对象101 102       //5.Web.config中mongodbConnection为MongoServer地址,可以使用;mongodbDatabase 为数据库名称,可以改成想要的103     }

View Code

  这里面有insert,find,findone,push,pull,delete,replace,update这些方法,可能根据项目不同需求还要改一些,到时我再更新,不过这东西我也就是记在这,而已。。。如果别人要用,就拿走吧,写的不好,别喷。

  然后其实我有几个问题,大家如果谁知道可以给我留言,小二先谢谢啦。

  1.在我的数据对象里,如果一个属性我没有赋值,怎么样能让它不插入,也就是只插入有值得字段?

  2.我在push的时候,不知道为什么mongo会帮我生成一个属性“_t”:"ClassName",这里的ClassName其实是我传入的对象的名称,这个想制止它,要怎么玩儿?

  转载请注明
      作者:李小二的春天
      地址:http://www.cnblogs.com/LittleTwoLee/p/5086316.html