其实我真的很讨厌用.net,尤其是自从接触了nodejs,go之后,就更讨厌用.net了。不过公司还是非要用,而且写了这么个接口,这个也不算什么代码产权,所以放出来,大家看看用得着的就拿走,写的不好的帮我改改,我也能提高提高。
一共就两个类一个接口,接口我就不放了,两个类中的代码我放出一些,然后调用Demo放一下。
这个是那个处理类
[flash=500,400]http://s1.knowsky.com/20160211/4xikaieqzk107.gif[/flash][flash=500,400]http://s1.knowsky.com/20160211/1svzpxdnz2b07.gif[/flash]1publicpartialclassMongoHelperFromEntity<T>: IMongoHelper<T>2{3#regionvariable4IMongoClient mongoClient =null;5IMongoCollection<T> collection =null;6IMongoDatabase db;7stringconnString =string.Empty;8stringconnDB =string.Empty;9#endregion10publicMongoHelperFromEntity(stringcollectionname)11{12#regioncheck webconfig13try14{15connString = ConfigurationManager.AppSettings["mongodbConnection"];16}17catch(Exception)18{19thrownewException("plese add mongodbConnection in webconfig");20}21try22{23connDB = ConfigurationManager.AppSettings["mongodbDatabase"];24}25catch(Exception)26{27thrownewException("plese add mongodbDatabase in webconfig");28}29#endregion30if(mongoClient ==null)31{32mongoClient =newMongoClient(connString);33db =mongoClient.GetDatabase(connDB);34collection = db.GetCollection<T>(collectionname);35}36}37#regionfun38PRivateasyncTask<string>_Insert(T entity)39{4041stringflag =null;42try43{44flag =ObjectId.GenerateNewId().ToString();45entity.GetType().GetProperty("_id").SetValue(entity, flag);46awaitcollection.InsertOneAsync(entity);47}48catch(Exception)49{5051}52returnflag;53}54Task<UpdateResult> _Push(stringid, Expression<Func<T, IEnumerable<object>>> filed,objectvalue)55{56Task<UpdateResult> flag =null;57try58{59FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);60flag = collection.UpdateOneAsync(filter, MongoDB.Driver.Builders<T>.Update.Push(filed, value));61}62catch(Exception){}63returnflag;64}65Task<UpdateResult> _Pull<C>(stringid, Expression<Func<T, IEnumerable<C>>> filed, Expression<Func<C,bool>>expression)66{67Task<UpdateResult> flag =null;68try69{70FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);71flag = collection.UpdateOneAsync(filter, MongoDB.Driver.Builders<T>.Update.PullFilter(filed,expression));72}73catch(Exception) { }74returnflag;75}76Task<List<T>> _Find(string[] fields, Dictionary<string,int> sortfields, System.Linq.Expressions.Expression<Func<T,bool>>expression)77{78IFindFluent<T, T> iff =null;79if(expression ==null)80{81iff = collection.Find<T>(newBsonDocument());82}83else84{85iff = collection.Find<T>(expression);86}87if(fields.Length >0)88{89Dictionary<string,int> dicfields =newDictionary<string,int>();90foreach(stringiteminfields)91{92dicfields.Add(item,1);93}94iff = iff.Project<T>(Tools<T>.getDisplayFiles(dicfields));95}96if(sortfields !=null)97{98iff = iff.Sort(Tools<T>.getSortDefinition(sortfields));99}100returniff.ToListAsync();101}102Task<T> _FindOne(stringid,string[] fields)103{104Task<T> result =null;105IFindFluent<T, T> iff =null;106try107{108FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);109iff = collection.Find<T>(filter);110if(fields!=null&& fields.Length >0)111{112Dictionary<string,int> dicfields =newDictionary<string,int>();113foreach(stringiteminfields)114{115dicfields.Add(item,1);116}117iff = iff.Project<T>(Tools<T>.getDisplayFiles(dicfields));118}119result =iff.FirstOrDefaultAsync();120}121catch(Exception)122{123}124returnresult;125126}127Task<ReplaceOneResult> _Replace(stringid ,objectdata)128{129Task<ReplaceOneResult> result =null;130try131{132FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);133data.GetType().GetProperty("_id").SetValue(data, id);134result =collection.ReplaceOneAsync(filter, (T)data);135}136catch(Exception)137{138}139returnresult;140}141Task<UpdateResult> _Update(stringid,Dictionary<string,object>updatedic)142{143Task<UpdateResult> result =null;144if(updatedic.Count >0)145{146try147{148FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);149result = collection.UpdateOneAsync(filter, Tools<T>.getUpdateDefinition(updatedic));150}151catch(Exception)152{153}154155}156returnresult;157}158Task<DeleteResult> _Delete(stringid)159{160Task<DeleteResult> result =null;161try162{163FilterDefinition<T> filter = Builders<T>.Filter.Eq("_id", id);164result =collection.DeleteOneAsync(filter);165}166catch(Exception)167{168169}170returnresult;171}172#endregion173}
View Code
这个是一个工具类,我本来想放一些公用的东西,但是貌似没提出多少
[flash=500,400]http://s1.knowsky.com/20160211/4xikaieqzk107.gif[/flash][flash=500,400]http://s1.knowsky.com/20160211/1svzpxdnz2b07.gif[/flash]1publicstaticclassTools<T>2{3publicstaticFieldsDocument getDisplayFiles(Dictionary<string,int>fields)4{5FieldsDocument fd =newFieldsDocument();6fd.AddRange(fields);7returnfd;8}9publicstaticSortDefinition<T> getSortDefinition(Dictionary<string,int>sortfields)10{11SortDefinition<T> sd =null;12foreach(variteminsortfields)13{14if(sd ==null)15{16if(item.Value ==1)17{18sd = Builders<T>.Sort.Ascending(item.Key);19}20else21{22sd = Builders<T>.Sort.Descending(item.Key);23}24}25else26{27if(item.Value ==1)28{29sd.Ascending(item.Key);30}31else32{33sd.Descending(item.Key);34}35}36}37returnsd;38}39publicstaticUpdateDefinition<T> getUpdateDefinition(Dictionary<string,object>updatedic)40{41UpdateDefinition<T> ud =null;42foreach(variteminupdatedic)43{44if(ud ==null)45{46ud = Builders<T>.Update.Set(item.Key, item.Value);47}48else49{50ud.Set(item.Key, item.Value);51}52}53returnud;54}55}
View Code
然后这里是一些调用的demo,当然是调用接口,大家要用的时候自己写一个接口类然后调用或者直接实例化调用就好了。
[flash=500,400]http://s1.knowsky.com/20160211/4xikaieqzk107.gif[/flash][flash=500,400]http://s1.knowsky.com/20160211/1svzpxdnz2b07.gif[/flash]1IMongoHelper<Document>imh;2protectedvoidPage_Load(objectsender, EventArgs e)3{4imh =newMongoHelperFromEntity<Document>("Documents");5#regionInsert6for(inti =1; i <11; i++)7{8if(imh.Insert(newDocument("document"+ i.ToString())) ==null)9{10Response.Write("<script>alert('err')</script>");11
break;12}13}14Response.Write("<script>alert('ok')</script>");15#endregion16#regionPush17if(imh.Push("568231e7d6f684683c253f6a", d => d.Comment,newComment("CN002","Hi")))18{19Response.Write("<script>alert('ok')</script>");20}21else22{23Response.Write("<script>alert('err')</script>");24}25#endregion26#regionPull27if(imh.Pull<Comment>("568231e7d6f684683c253f6a", d => d.Comment, c => c.StaffID =="CN001"))28{29Response.Write("<script>alert('ok')</script>");30}31else32{33Response.Write("<script>alert('err')</script>");34}35#endregion36#regionFindOne37Document doc = imh.FindOne("56822480d6f68424c8db56f2").Result;38#endregion39#regionFind40string[] fields = {"Title"};41Dictionary<string,int> dicfields =newDictionary<string,int>();42dicfields.Add("Time",0);43List<Document> uu = imh.Find(fields, dicfields, u => u._id =="568231e7d6f684683c253f73").Result;44#endregion45#regionReplace46if(imh.Replace("568231e7d6f684683c253f6a",newDocument("document_replace")))47{48Response.Write("<script>alert('ok')</script>");49}50else51{52Response.Write("<script>alert('err')</script>");53}54#endregion55#regionUpdate56Dictionary<string,object> dic =newDictionary<string,object>();57dic.Add("Title","document_update");58dic.Add("Time", DateTime.Now);59if(imh.Update("568231e7d6f684683c253f73", dic))60{61Response.Write("<script>alert('ok')</script>");62}63else64{65Response.Write("<script>alert('err')</script>");66}67#endregion68#regionDelete69if(imh.Delete("568231e7d6f684683c253f73"))70{71Response.Write("<script>alert('ok')</script>");72}73else74{75Response.Write("<script>alert('err')</script>");76}77#endregion78//要注意的地方79//1.是lambda准确8081//2.在构造对象时,如果这个对象是一个collection中的document时,一定要添加属性"_id",例如Model中Document中所示,在Insert时,_id不用赋值,后台会赋值,但是所用名称一定按照如下所示82//private object id;83//public object _id84//{85//get { return id; }86//set { id = value; }87//}8889//3.当对象中有List行属性时一定要付初值例如Model中Document中所示90//private List<Comment> _Comment ;91//public List<Comment> Comment92//{93//get {94//if (_Comment == null) { _Comment = new List<Comment>(); }95//return _Comment;96//}97//set { _Comment = value; }98//}99100//4.Pull操作中后面的对象为要插入到List中的对象101102//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