码迷,mamicode.com
首页 > 数据库 > 详细

mongo DB for C#

时间:2015-06-01 16:40:07      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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

 

mongo DB for C#

标签:

原文地址:http://www.cnblogs.com/w2011/p/4544104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!