標籤:des style blog http io ar color os 使用
mongodb c# driver(驅動)介紹
目前基於C#的mongodb驅動有兩種,分別是官方驅動()和samus驅動()。
本次我們只示範官方驅動的使用方法。
官方驅動文檔查看
第一步:引用驅動dll
引用驅動有兩種方式:
1. 根據上面的下載對應的版本,然後引用到項目中。
2. 在項目的引用上右擊->管理NuGet程式包(首先確保安裝了nuget擴充包)->聯機搜尋官方驅動dll(搜尋條件是 “Official MongoDB”)->安裝成功後會引用3個dll(MongoDB.Driver和MongoDB.Bson,Newtonsoft.Json)。
第二步:構造MongodbHelper類
代碼如下:
using MongoDB.Driver;using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Server.DAL.DBHelper{ public sealed class MongodbHelper { static public readonly MongodbHelper Instance = new MongodbHelper(); private MongoDatabase db; private MongodbHelper() { //http://www.studyofnet.com/news/337.html //mongodb://[username:[email protected]]host1[:port1][,host2[:port2],…[,hostN[:portN]]][/[database][?options]] string strconn = "mongodb://sa:[email protected]:27017"; string dbName = "test"; MongoDB.Driver.MongoClient mongoClient = new MongoClient(strconn); MongoServer server = mongoClient.GetServer(); db = server.GetDatabase(dbName); } public MongoDatabase DB { get { return db; } } public MongoCollection this[string value] { get { return db.GetCollection(value); } } }}
第三步:添加實體物件
在此建立的是一個複雜person對象,如下代碼:
public class Test:BaseEntity{}public class PersonType : BaseEntity{ public string Code { get; set; } public string Display { get; set; }}public class Person : BaseEntity{ //如果對應多個分類,則格式為:,3,34,2 public string PersonType { get; set; } public string Name { get; set; } public bool Sex { get; set; } public int Age { get; set; } public DateTime AddTime { get; set; } public List<Address> Addresses { get; set; } public List<string> Courses { get; set; }}public class Address{ public string Province { get; set; } public string City { get; set; }}
BaseEntity說明
BaseEntity中放的是mongodb資料庫中自動產生的_id(類型是ObjectId)
public class BaseEntity{ /// <summary> /// 欄位對應,告訴mongodb這個欄位在資料庫中對應_id /// </summary> [BsonId] //告訴mongodb這個欄位在資料庫中的類型是ObjectId [BsonRepresentation(BsonType.ObjectId)] public string _id { get; set; }}
第四步:建立ApiController
建立ApiController基類BaseApiController
BaseApiController中會初始化一些變數,代碼如下:
public class BaseApiController : ApiController { public int skip, take; public MongoDatabase db; public MongoCollection col = null;//用於直接返回查詢的json public BaseApiController(string collectionName) { skip = GetIntRequest("skip"); take = GetIntRequest("take"); if (skip == 0 && take == 0) { take = int.MaxValue; } db = Server.DAL.DBHelper.MongodbHelper.Instance.DB; col = db.GetCollection(collectionName); } public string GetStringRequest(string paramter) { return HttpContext.Current.Request.QueryString[paramter] ?? ""; } public int GetIntRequest(string paramter) { string tmp = HttpContext.Current.Request.QueryString[paramter] ?? ""; int tag = 0; int.TryParse(tmp, out tag); return tag; } }
建立TestController繼承BaseApiController
我們就用TestController來示範CURD.
具體代碼如下,不再做詳細說明:
public class TestController : Filter.BaseApiController{ public TestController() : base("Person") { } public string Post([FromBody]object value) { var model = JsonConvert.DeserializeObject<Person>(value.ToString()); model._id = ObjectId.GenerateNewId().ToString(); try { col.Insert(model); return model._id; } catch (WebException ex) { throw ex; } } public object Get() { try { IEnumerable<Person> queryable = col.AsQueryable<Person>(); Func<Person, bool> where = null; //有多少條件並多少條件 //like //var name = GetStringRequest("Name"); if (!string.IsNullOrEmpty(name)) { where = c => c.Name.Contains(name); queryable = queryable.Where(where); } //單個條件等值查詢 var personType = GetStringRequest("personType"); if (!string.IsNullOrEmpty(personType)) { where = c => c.PersonType == personType; queryable = queryable.Where(where); } //嵌套數組查詢 var course = GetStringRequest("course"); if (!string.IsNullOrEmpty(course)) { where = c => c.Courses.Contains(course); queryable = queryable.Where(where); } //嵌套實體集合查詢---查數量 var address = GetStringRequest("address"); if (!string.IsNullOrEmpty(address)) { where = c => c.Addresses.Count > GetIntRequest("address"); queryable = queryable.Where(where); } var personList = queryable.OrderByDescending(c => c._id).Skip(skip).Take(take).ToList(); var count = queryable.Count(); var data = new { count = count, dataList = personList }; return data; } catch (WebException ex) { throw ex; } } public Person Get(string id) { try { var model = col.AsQueryable<Person>().FirstOrDefault(c => c._id == id); return model; } catch (WebException ex) { throw ex; } } //部分欄位修改模式,只修改需要修改的欄位。缺點是只能修改單個屬性,對於嵌套數組和嵌套實體集合無法修改 public int Put(string id, [FromBody]object value) { try { var query = new QueryDocument { { "_id", ObjectId.Parse(id) } }; var dicData = JsonConvert.DeserializeObject<Dictionary<string, object>>(value.ToString()); var update = new UpdateDocument { { "$set", new QueryDocument(dicData) } }; col.Update(query, update); return 1; } catch (WebException ex) { throw ex; } } //完全修改模式,先查後改,支援任意類型的對象的修改。缺點是需要先查詢一次 public int Put([FromBody]object value) { try { var model = JsonConvert.DeserializeObject<Person>(value.ToString()); col.Save(model); return 1; } catch (WebException ex) { throw ex; } } public void Delete(string id) { try { var query = new QueryDocument { { "_id", ObjectId.Parse(id) } }; col.Remove(query); } catch (WebException ex) { throw ex; } }}
第五步:CURD示範
在這裡我們使用一個工具Fiddler2示範。
添加
mongodb c# driver(驅動)介紹及CURD