如何在.Net中使用MongoDB

今天测试了一下在.Net环境下使用MongoDb数据库。

首先去下载MongoDb的驱动,官方有提供。分1.10版本与2.0版本,2.0版本是4.5Framekwork开发,4.5以下的请下载1.10版本,否则编译不过去。

下载好以后项目中引入MongoDB.Bson.dll与MongoDB.Driver.dll。(2.0版本的dll更多)

BLL代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace Soffice.DeveloperTools.Bll
{
    public class CsSystem
    {
        /// <summary>
        /// 获取分页列表数据
        /// </summary>
        /// <param name="total">记录总数</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">每页显示多少条</param>
        /// <param name="where">where条件</param>
        /// <returns></returns>
        public static List<ModelDb.CsSystem> GetList(out int total, int pageIndex, int pageSize, ModelMvc.CsSystemWhere where)
        {
            MongoClient client = new MongoClient("mongodb://localhost");
            MongoServer server = client.GetServer();
            MongoDatabase database = server.GetDatabase("CoreSystem");
            MongoCollection collection = database.GetCollection<ModelDb.CsSystem>("CsSystem");
            total = Convert.ToInt32(collection.Count());
            return collection.FindAllAs<ModelDb.CsSystem>().Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
        }

        /// <summary>
        /// 获取DtGrid列表数据
        /// </summary>
        /// <param name="gridParam">Grid传入参数</param>
        /// <returns></returns>
        public static string GetGrid(string gridParam)
        {
            ModelMvc.CsSystemDtGrid grid = CommonFunction.Deserialize<ModelMvc.CsSystemDtGrid>(gridParam);

            int total = 0;
            List<ModelDb.CsSystem> listDb = GetList(out total, grid.nowPage, grid.pageSize, grid.parameters);
            List<ModelMvc.CsSystemGridData> gridDatas = new List<ModelMvc.CsSystemGridData>();
            foreach (ModelDb.CsSystem m in listDb)
            {
                gridDatas.Add(new ModelMvc.CsSystemGridData
                {
                    Id = m.Id,
                    TypesName = CsDict.CsSystem_Types.Where(w => w.Id == m.Types).Select(s => s.ItemValue).FirstOrDefault(),
                    Names = m.Names,
                    Code = m.Code,
                    EntryUrl = m.EntryUrl,
                    Remark = m.Remark,
                    IsEnabledName = m.IsEnabled ? "" : ""
                });
            }

            grid.isSuccess = true;
            grid.recordCount = total;
            grid.exhibitDatas = gridDatas;

            return CommonFunction.Serialize(grid);
        }

        /// <summary>
        /// 根据主键id获取编辑数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static ModelMvc.CsSystemForm GetEditInfo(int id)
        {
            MongoClient client = new MongoClient("mongodb://localhost");
            MongoServer server = client.GetServer();
            MongoDatabase database = server.GetDatabase("CoreSystem");
            MongoCollection collection = database.GetCollection<ModelDb.CsSystem>("CsSystem");
            var query = Query.EQ("_id", id);
            ModelDb.CsSystem m = collection.FindOneAs<ModelDb.CsSystem>(query);
            return new ModelMvc.CsSystemForm
            {
                Id = m.Id,
                Types = m.Types,
                Names = m.Names,
                Code = m.Code,
                EntryUrl = m.EntryUrl,
                IsEnabled = m.IsEnabled,
                Remark = m.Remark
            };
        }

        /// <summary>
        /// 保存新增
        /// </summary>
        /// <param name="m">表单数据</param>
        /// <returns></returns>
        public static bool SaveAdd(ModelMvc.CsSystemForm m)
        {
            CommonValid valid = new CommonValid(m);
            if (valid.IsValid)
            {
                MongoClient client = new MongoClient("mongodb://localhost");
                MongoServer server = client.GetServer();
                MongoDatabase database = server.GetDatabase("CoreSystem");
                MongoCollection collection = database.GetCollection<ModelDb.CsSystem>("CsSystem");
                return collection.Insert(new ModelDb.CsSystem
                {
                    Id = m.Id,
                    Types = m.Types,
                    Names = m.Names,
                    Code = m.Code,
                    EntryUrl = m.EntryUrl,
                    IsEnabled = m.IsEnabled,
                    Remark = m.Remark
                }).Ok;
            }
            else
            {
                throw new ExceptionValid(valid);
            }
        }

        /// <summary>
        /// 保存新增
        /// </summary>
        /// <param name="m">表单数据</param>
        /// <returns></returns>
        public static bool SaveEdit(ModelMvc.CsSystemForm m)
        {
            CommonValid valid = new CommonValid(m);
            if (valid.IsValid)
            {
                MongoClient client = new MongoClient("mongodb://localhost");
                MongoServer server = client.GetServer();
                MongoDatabase database = server.GetDatabase("CoreSystem");
                MongoCollection collection = database.GetCollection<ModelDb.CsSystem>("CsSystem");
                return collection.Save(new ModelDb.CsSystem
                {
                    Id = m.Id,
                    Types = m.Types,
                    Names = m.Names,
                    Code = m.Code,
                    EntryUrl = m.EntryUrl,
                    IsEnabled = m.IsEnabled,
                    Remark = m.Remark
                }).Ok;
            }
            else
            {
                throw new ExceptionValid(valid);
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static bool SaveDelete(int id)
        {
            MongoClient client = new MongoClient("mongodb://localhost");
            MongoServer server = client.GetServer();
            MongoDatabase database = server.GetDatabase("CoreSystem");
            var collection = database.GetCollection<ModelDb.CsSystem>("CsSystem");
            var query = Query.EQ("_id", id);
            return collection.Remove(query).Ok;
        }
    }
}

Model代码:

using System;

namespace Soffice.DeveloperTools.ModelDb
{
    public class CsSystem
    {
        /// <summary>
        /// Id
        /// </summary>        
        public int Id { get; set; }
        /// <summary>
        /// 1.子系统,2.其它第三方系统
        /// </summary>        
        public int Types { get; set; }
        /// <summary>
        /// Names
        /// </summary>        
        public string Names { get; set; }
        /// <summary>
        /// Code
        /// </summary>        
        public string Code { get; set; }
        /// <summary>
        /// EntryUrl
        /// </summary>        
        public string EntryUrl { get; set; }
        /// <summary>
        /// Remark
        /// </summary>        
        public string Remark { get; set; }
        /// <summary>
        /// IsEnabled
        /// </summary>        
        public bool IsEnabled { get; set; }
    }
}

注意:Model中有些关键字MongoDb会自动转换掉。例如像:"Id"这个属性,如果存在MongoDb中会被转成"_id"。

有些时候查询条件查不到的时候请去数据库中检查真实存在的属性名称。并且注意要区分大小写。

 

如有转载请流下原创地址。

posted @ 2015-09-01 19:00  魏巍(QQ:68235081)  阅读(3322)  评论(0编辑  收藏  举报