標籤:
作為系列的最後一篇,得要說說C#驅動對mongodb的操作,目前驅動有兩種:官方驅動和samus驅動,不過我個人還是喜歡後者,
因為提供了豐富的linq操作,相當方便。
官方驅動:https://github.com/mongodb/mongo-csharp-driver/downloads。下載後,還提供了一個酷似msdn的協助文檔。
samus驅動:https://github.com/samus/mongodb-csharp/downloads。
下面就具體看看samus驅動,https://github.com/samus/mongodb-csharp/blob/master/examples/Simple/Main.cs上面提供了
一個簡單的demo,大體上看看我們就知道怎麼玩了。
一: 實踐
1:我們建立一個Person實體,MongoAlias特性表示取別名,這裡的ID值將會覆蓋掉資料庫自動產生的_id。
1 #region 資料實體
2 /// <summary>
3 /// 資料實體
4 /// </summary>
5 public class Person
6 {
7 [MongoAlias("_id")]
8 public string ID { get; set; }
9
10 public string Name { get; set; }
11
12 public int Age { get; set; }
13
14 public DateTime CreateTime { get; set; }
15 }
16 #endregion
2:初始化一些變數
1 string connectionString = string.Empty;
2
3 string databaseName = string.Empty;
4
5 string collectionName = string.Empty;
6
7 static MongodbHelper<T> mongodb;
8
9 #region 初始化操作
10 /// <summary>
11 /// 初始化操作
12 /// </summary>
13 public MongodbHelper()
14 {
15 connectionString = "Server=127.0.0.1:2222";
16 databaseName = "shopex";
17 collectionName = "person";
18 }
19 #endregion
3:為了方便T的繼承類使用linq功能,我們還需要映射一下。
1 #region 實現linq查詢的映射配置
2 /// <summary>
3 /// 實現linq查詢的映射配置
4 /// </summary>
5 public MongoConfiguration configuration
6 {
7 get
8 {
9 var config = new MongoConfigurationBuilder();
10
11 config.Mapping(mapping =>
12 {
13 mapping.DefaultProfile(profile =>
14 {
15 profile.SubClassesAre(t => t.IsSubclassOf(typeof(T)));
16 });
17 mapping.Map<T>();
18 mapping.Map<T>();
19 });
20
21 config.ConnectionString(connectionString);
22
23 return config.BuildConfiguration();
24 }
25 }
26 #endregion
4:下面是一些基本的CURD的代碼,跟寫EF代碼很類似,寫起來好舒服。
1 #region 插入操作
2 /// <summary>
3 /// 插入操作
4 /// </summary>
5 /// <param name="person"></param>
6 /// <returns></returns>
7 public void Insert(T t)
8 {
9 using (Mongo mongo = new Mongo(configuration))
10 {
11 try
12 {
13 mongo.Connect();
14
15 var db = mongo.GetDatabase(databaseName);
16
17 var collection = db.GetCollection<T>(collectionName);
18
19 collection.Insert(t, true);
20
21 mongo.Disconnect();
22
23 }
24 catch (Exception)
25 {
26 mongo.Disconnect();
27 throw;
28 }
29 }
30 }
31 #endregion
32
33 #region 更新操作
34 /// <summary>
35 /// 更新操作
36 /// </summary>
37 /// <param name="person"></param>
38 /// <returns></returns>
39 public void Update(T t, Expression<Func<T, bool>> func)
40 {
41 using (Mongo mongo = new Mongo(configuration))
42 {
43 try
44 {
45 mongo.Connect();
46
47 var db = mongo.GetDatabase(databaseName);
48
49 var collection = db.GetCollection<T>(collectionName);
50
51 collection.Update<T>(t, func, true);
52
53 mongo.Disconnect();
54
55 }
56 catch (Exception)
57 {
58 mongo.Disconnect();
59 throw;
60 }
61 }
62 }
63 #endregion
64
65 #region 擷取集合
66 /// <summary>
67 ///擷取集合
68 /// </summary>
69 /// <param name="person"></param>
70 /// <returns></returns>
71 public List<T> List(int pageIndex, int pageSize, Expression<Func<T, bool>> func, out int pageCount)
72 {
73 pageCount = 0;
74
75 using (Mongo mongo = new Mongo(configuration))
76 {
77 try
78 {
79 mongo.Connect();
80
81 var db = mongo.GetDatabase(databaseName);
82
83 var collection = db.GetCollection<T>(collectionName);
84
85 pageCount = Convert.ToInt32(collection.Count());
86
87 var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1))
88 .Take(pageSize).Select(i => i).ToList();
89
90 mongo.Disconnect();
91
92 return personList;
93
94 }
95 catch (Exception)
96 {
97 mongo.Disconnect();
98 throw;
99 }
100 }
101 }
102 #endregion
103
104 #region 讀取單條記錄
105 /// <summary>
106 ///讀取單條記錄
107 /// </summary>
108 /// <param name="person"></param>
109 /// <returns></returns>
110 public T Single(Expression<Func<T, bool>> func)
111 {
112 using (Mongo mongo = new Mongo(configuration))
113 {
114 try
115 {
116 mongo.Connect();
117
118 var db = mongo.GetDatabase(databaseName);
119
120 var collection = db.GetCollection<T>(collectionName);
121
122 var single = collection.Linq().FirstOrDefault(func);
123
124 mongo.Disconnect();
125
126 return single;
127
128 }
129 catch (Exception)
130 {
131 mongo.Disconnect();
132 throw;
133 }
134 }
135 }
136 #endregion
137
138 #region 刪除操作
139 /// <summary>
140 /// 刪除操作
141 /// </summary>
142 /// <param name="person"></param>
143 /// <returns></returns>
144 public void Delete(Expression<Func<T, bool>> func)
145 {
146 using (Mongo mongo = new Mongo(configuration))
147 {
148 try
149 {
150 mongo.Connect();
151
152 var db = mongo.GetDatabase(databaseName);
153
154 var collection = db.GetCollection<T>(collectionName);
155
156 //這個地方要注意,一定要加上T參數,否則會當作object類型處理
157 //導致刪除失敗
158 collection.Remove<T>(func);
159
160 mongo.Disconnect();
161
162 }
163 catch (Exception)
164 {
165 mongo.Disconnect();
166 throw;
167 }
168 }
169 }
170 #endregion
5. 好,我們開一下2222連接埠,由於前前篇我已經把這個mongodb做成了服務,現在就直接連過去了,並做一下對Name的索引。
6. 一切準備妥當,我們做下基本的操作,比如這裡我添加一千條資料,注意我開啟的是安全模式,如果插入不成功,將會拋出異常。
<1> Add:
1 static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //插入1000條資料
6 for (int i = 0; i < 1000; i++)
7 {
8 helper.Insert(new Person()
9 {
10 ID = Guid.NewGuid().ToString(),
11 Name = "jack" + i,
12 Age = i,
13 CreateTime = DateTime.Now
14 });
15 }
16
17 Console.WriteLine("插入成功");
18
19 Console.Read();
20 }
乍一看顯示的資料以為有問題,為什麼沒有出現jack0或者jack999,不過find的一下後心情舒坦了。
<2> update: 這裡就把jack941的名字改掉“mary”
1 static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //修改jack941改成mary
6 var single = helper.Single(i => i.Name == "jack941");
7 single.Name = "mary";
8 helper.Update(single, i => i.ID == single.ID);
9
10 Console.WriteLine("修改成功");
11 Console.Read();
12 }
<3>Delete: 刪除mary這條記錄
1 static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 //刪除mary這個記錄
6 helper.Delete(i => i.Name == "mary");
7
8 Console.WriteLine("刪除成功");
9 Console.Read();
10 }
<4> list操作: 這裡我擷取一下名字裡面帶9的人數列表
1 static void Main(string[] args)
2 {
3 MongodbHelper<Person> helper = new MongodbHelper<Person>();
4
5 int pagecount;
6
7 //擷取名字裡面帶9的人數
8 var list = helper.List(1, 20, i => i.Name.Contains("9"), out pagecount);
9
10 Console.Read();
11 }
總的運行代碼
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Configuration;using System.Linq.Expressions;using MongoDB.Configuration;using MongoDB.Linq;using MongoDB.Attributes;namespace MongoDB.Test{ public class MongodbHelper<T> where T : class { string connectionString = string.Empty; string databaseName = string.Empty; string collectionName = string.Empty; static MongodbHelper<T> mongodb; #region 初始化操作 /// <summary>/// 初始化操作/// </summary> public MongodbHelper() { connectionString = "Server=127.0.0.1:2222"; databaseName = "shopex"; collectionName = "person"; } #endregion #region 實現linq查詢的映射配置 /// <summary>/// 實現linq查詢的映射配置/// </summary> public MongoConfiguration configuration { get { var config = new MongoConfigurationBuilder(); config.Mapping(mapping => { mapping.DefaultProfile(profile => { profile.SubClassesAre(t => t.IsSubclassOf(typeof(T))); }); mapping.Map<T>(); mapping.Map<T>(); }); config.ConnectionString(connectionString); return config.BuildConfiguration(); } } #endregion #region 插入操作 /// <summary>/// 插入操作/// </summary>/// <param name="person"></param>/// <returns></returns> public void Insert(T t) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); collection.Insert(t, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 更新操作 /// <summary>/// 更新操作/// </summary>/// <param name="person"></param>/// <returns></returns> public void Update(T t, Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); collection.Update<T>(t, func, true); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 擷取集合 /// <summary>///擷取集合/// </summary>/// <param name="person"></param>/// <returns></returns> public List<T> List(int pageIndex, int pageSize, Expression<Func<T, bool>> func, out int pageCount) { pageCount = 0; using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); pageCount = Convert.ToInt32(collection.Count()); var personList = collection.Linq().Where(func).Skip(pageSize * (pageIndex - 1)) .Take(pageSize).Select(i => i).ToList(); mongo.Disconnect(); return personList; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 讀取單條記錄 /// <summary>///讀取單條記錄/// </summary>/// <param name="person"></param>/// <returns></returns> public T Single(Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); var single = collection.Linq().FirstOrDefault(func); mongo.Disconnect(); return single; } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion #region 刪除操作 /// <summary>/// 刪除操作/// </summary>/// <param name="person"></param>/// <returns></returns> public void Delete(Expression<Func<T, bool>> func) { using (Mongo mongo = new Mongo(configuration)) { try { mongo.Connect(); var db = mongo.GetDatabase(databaseName); var collection = db.GetCollection<T>(collectionName); //這個地方要注意,一定要加上T參數,否則會當作object類型處理//導致刪除失敗 collection.Remove<T>(func); mongo.Disconnect(); } catch (Exception) { mongo.Disconnect(); throw; } } } #endregion } #region 資料實體 /// <summary>/// 資料實體/// </summary> public class Person { [MongoAlias("_id")] public string ID { get; set; } public string Name { get; set; } public int Age { get; set; } public DateTime CreateTime { get; set; } } #endregion}
趁著3天的休假,不斷的努力終於把這個系列寫完了,很感謝一直關注此系列的朋友。
8天學通MongoDB——第八天 驅動實踐