MongoDB的驅動有好幾個,分布式檔案儲存體的資料庫開源項目MongoDB裡使用的是github.com/samus/mongodb-csharp,monogodb-csharp不是強型別,使用起來不方便。轉向使用支援強型別訪問MongoDB的NoRM C# driver。NoRM 驅動和MongoDB-CSharp的一個區別的地方就是NoRM使用強型別的類操作MongoDB-CSharp的Document類。
使用NoRM很簡單,引用NoRM.dll就可以了,下面的例子是一個控制台程式:
模型類,代表儲存到資料庫的資料
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Norm;
namespace FirstMongoDb
{
public class Customer: IHaveIdentifier
{
public ObjectId _id { get; set; }
public string Name { get; set; }
public DateTime LastOrderUtc { get; set; }
public List<string> OrderedItems { get; set; }
public Customer()
{
OrderedItems = new List<string>();
}
}
}
這個足夠簡單了,下面我們連到資料庫
public class MongoDbDataContext : IDisposable
{
private readonly MongoQueryProvider provider;
public MongoQueryProvider Provider
{
get { return provider; }
}
public static string DatabaseName { get; set; }
public MongoDbDataContext()
{
if ( string.IsNullOrEmpty( DatabaseName ) )
{
throw new InvalidOperationException( "You must set the static DatabaseName property." );
}
provider = new MongoQueryProvider(
new Mongo( DatabaseName, "127.0.0.1", "27017", null ) );
}
使用NoRM去冬串連到資料需要提供一個資料庫名,伺服器位址和連接埠,參看上述紅色代碼。
插入一個對象到資料庫
private static void Insert()
{
Customer c = new Customer();
c.Name = "Jake";
c.LastOrderUtc = DateTime.UtcNow;
c.OrderedItems.Add("frappa");
c.OrderedItems.Add( "beer" );
c.OrderedItems.Add( "redbull!" );
c.OrderedItems.Add( "wings" );
using ( MongoDbDataContext ctx = new MongoDbDataContext() )
{
ctx.Add(c);
}
}
使用LINQ查詢資料庫
using ( MongoDbDataContext ctx = new MongoDbDataContext() )
{
var query =
from c in ctx.Customers
where c.Name == "Michael"
orderby c.LastOrderUtc descending
select c;
foreach (var customer in query)
{
Console.WriteLine("{0} bought {1}",
customer.Name,
customer.OrderedItems.FirstOrDefault()
);
}
}
參考:Using MongoDB with the NoRM driver