(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
/// <summary>
/// 数据库连接
/// </summary>
private const string connUrl = "mongodb://127.0.0.1:27017";
/// <summary>
/// 指定的数据库
/// </summary>
private const string dbName = "testdb"; protected static IMongoClient _client;
protected static IMongoDatabase _database; void Load(){ var url = new MongoUrl(connUrl);
var settings = MongoClientSettings.FromUrl(url);
settings.Credentials = new List<MongoCredential>()
{
MongoCredential.CreateCredential(dbName, "admin", "")
};
//创建数据连接
_client = new MongoClient();_database = _client.GetDatabase(dbName); }
获取数据
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