mongo DB for C#

(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
技术分享

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。