如何在.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"。

有些時候查詢條件查不到的時候請去數據庫中檢查真實存在的屬性名稱。並且注意要區分大小寫。

 

如有轉載請流下原創地址。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM