(1)Download the MongoDB C#驱动.
http://www.nuget.org/packages/mongocsharpdriver/.
(2) Add Reference to C# 驱动 DLLs
1MongoDB.Bson.dll
2MongoDB.Driver.dll
3MongoDB.Driver.Core.dll
或者 Nuget 下载
VS 2012/13 TOOLS -> Library Package Manager –> Manage NuGet Package for Solution,然后选online,搜索mongodb,然后下载driver。
(3)连接Mongo DB
1 /// <summary>
2 /// 数据库连接
3 /// </summary>
4 private const string connUrl = "mongodb://127.0.0.1:27017";
5 /// <summary>
6 /// 指定的数据库
7 /// </summary>
8 private const string dbName = "testdb";
9
10 protected static IMongoClient _client;
11 protected static IMongoDatabase _database;
12
13 void Load(){
14
15 var url = new MongoUrl(connUrl);
16 var settings = MongoClientSettings.FromUrl(url);
17 settings.Credentials = new List<MongoCredential>()
18 {
19 MongoCredential.CreateCredential(dbName, "admin", "123456")
20 };
21 //创建数据连接
22 _client = new MongoClient();_database = _client.GetDatabase(dbName);
23
24 }
获取数据
async void GetData()
{
try
{
IMongoCollection<T_Role> collection = _database.GetCollection<T_Role>("dbo.T_Role");
var filter = new BsonDocument();
var data = await collection.Find(filter).ToListAsync();
if (data.Any())
{
gridControl1.BeginUpdate();
gridControl1.DataSource = data;
gridControl1.EndUpdate();
}
}
catch (FormatException e)
{
//记录日志
}}
备注如果这格式化与对像T_Role出现转换错误。那么请在实体表里添加 _Id