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 try
107 {
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 try
131 {
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 try
147 {
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 try
162 {
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 #endregion
173 }
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 else
21 {
22 sd = Builders<T>.Sort.Descending(item.Key);
23 }
24 }
25 else
26 {
27 if (item.Value == 1)
28 {
29 sd.Ascending(item.Key);
30 }
31 else
32 {
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 else
49 {
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