C# mongodb帮助类

Posted chenyucong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# mongodb帮助类相关的知识,希望对你有一定的参考价值。

这是在C#连接MongoDB的帮助类,所使用的驱动是在Vs2015的Nuget管理器中下载的mongodb驱动。

下载第一个,会自动下载下面的两个,不要删除。

 

在配置文件中配置连接字符串connStr和数据库名称dbName:

 1 <appSettings>
 2     <add key="webpages:Version" value="3.0.0.0"/>
 3     <add key="webpages:Enabled" value="false"/>
 4     <add key="ClientValidationEnabled" value="true"/>
 5     <add key="UnobtrusivejavascriptEnabled" value="true"/>
 6     <add key="dbName" value="demodb"/>
 7 </appSettings>
 8 <connectionStrings>
 9     <add name="connStr" connectionString="mongodb://127.0.0.1:27017"/>
10 </connectionStrings>

 

MongoDbHelper类:

  1 using Cong.Model;
  2 using MongoDB.Bson;
  3 using MongoDB.Driver;
  4 using System;
  5 using System.Collections.Generic;
  6 using System.Configuration;
  7 using System.Linq;
  8 
  9 namespace Cong.Utility
 10 {
 11     public class Db
 12     {
 13         private static readonly string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString();
 14 
 15         private static readonly string dbName = ConfigurationManager.AppSettings["dbName"].ToString();
 16 
 17         private static IMongoDatabase db = null;
 18 
 19         private static readonly object lockHelper = new object();
 20 
 21         private Db() { }
 22 
 23         public static IMongoDatabase GetDb()
 24         {
 25             if (db == null)
 26             {
 27                 lock (lockHelper)
 28                 {
 29                     if (db == null)
 30                     {
 31                         var client = new MongoClient(connStr);
 32                         db = client.GetDatabase(dbName);
 33                     }
 34                 }
 35             }
 36             return db;
 37         }
 38     }
 39 
 40     public class MongoDbHelper<T> where T : BaseEntity
 41     {
 42         private IMongoDatabase db = null;
 43 
 44         private IMongoCollection<T> collection = null;
 45 
 46         public MgHelper()
 47         {
 48             this.db = Db.GetDb();
 49             collection = db.GetCollection<T>(typeof(T).Name);
 50         }
 51 
 52         public T Insert(T entity)
 53         {
 54             var flag = ObjectId.GenerateNewId();
 55             entity.GetType().GetProperty("Id").SetValue(entity, flag);
 56             entity.State = "y";
 57             entity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 58             entity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 59 
 60             collection.InsertOneAsync(entity);
 61             return entity;
 62         }
 63 
 64         public void Modify(string id, string field, string value)
 65         {
 66             var filter = Builders<T>.Filter.Eq("Id", ObjectId.Parse(id));
 67             var updated = Builders<T>.Update.Set(field, value);
 68             UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
 69         }
 70 
 71         public void Update(T entity)
 72         {
 73             var old = collection.Find(e => e.Id.Equals(entity.Id)).ToList().FirstOrDefault();
 74 
 75             foreach (var prop in entity.GetType().GetProperties())
 76             {
 77                 var newValue = prop.GetValue(entity);
 78                 var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
 79                 if (newValue != null)
 80                 {
 81                     if (!newValue.ToString().Equals(oldValue.ToString()))
 82                     {
 83                         old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
 84                     }
 85                 }
 86             }
 87             old.State = "y";
 88             old.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
 89 
 90             var filter = Builders<T>.Filter.Eq("Id", entity.Id);
 91             ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
 92         }
 93 
 94         public void Delete(T entity)
 95         {
 96             var filter = Builders<T>.Filter.Eq("Id", entity.Id);
 97             collection.DeleteOneAsync(filter);
 98         }
 99 
100         public T QueryOne(string id)
101         {
102             return collection.Find(a => a.Id == ObjectId.Parse(id)).ToList().FirstOrDefault();
103         }
104 
105         public List<T> QueryAll()
106         {
107             return collection.Find(a => a.State.Equals("y")).ToList();
108         }
109     }
110 }


另外,我的实体类全部都继承自下面这个基类,里面有几个数据中常用的字段

BaseEntity:

 1 using MongoDB.Bson;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Text;
 6 using System.Threading.Tasks;
 7 
 8 namespace Cong.Model
 9 {
10     public abstract class BaseEntity
11     {
12         public ObjectId Id { get; set; }
13 
14         public string State { get; set; }
15 
16         public string CreateTime { get; set; }
17 
18         public string UpdateTime { get; set; }
19     }
20 }


 最后,这个是我在MVC的一个控制器的代码,使用了增改查的功能,以供参考,另外这个我是用模板生成的代码。

  1 using Cong.Model;
  2 using Cong.Utility;
  3 using MongoDB.Bson;
  4 using System.Web.Mvc;
  5 using WebApp.Models;
  6 
  7 namespace WebApp.Controllers
  8 {
  9 
 10     public partial class AuthController : BaseController
 11     {
 12         MgHelper<Auth> mg = new MgHelper<Auth>();
 13 
 14         public ActionResult Index()
 15         {
 16             return View();
 17         }
 18 
 19         [HttpGet]
 20         public ActionResult Create()
 21         {
 22             return View();
 23         }
 24 
 25         [HttpPost]
 26         public ActionResult Create(Auth auth)
 27         {
 28             mg.Insert(auth);
 29             return Content("<script>alert(\'success!\');window.location=\'/Auth/Create\';</script>");
 30         }
 31 
 32         [HttpGet]
 33         public ActionResult Modify()
 34         {
 35             AuthVM authvm = new AuthVM { Auths = mg.QueryAll() };
 36             return View(authvm);
 37         }
 38 
 39         [HttpPost]
 40         public ActionResult Modify(Auth auth, FormCollection form)
 41         {
 42             auth.Id = ObjectId.Parse(form["id"]);
 43             mg.Update(auth);
 44             return Content("<script>alert(\'success!\');window.location=\'/Auth/Modify\';</script>");
 45         }
 46 
 47         [HttpPost]
 48         public string Delete(string id)
 49         {
 50             mg.Modify(id, "State", "n");
 51             return "success!";
 52         }
 53     }
 54 
 55     public partial class RoleController : BaseController
 56     {
 57         MgHelper<Role> mg = new MgHelper<Role>();
 58 
 59         public ActionResult Index()
 60         {
 61             return View();
 62         }
 63 
 64         [HttpGet]
 65         public ActionResult Create()
 66         {
 67             return View();
 68         }
 69 
 70         [HttpPost]
 71         public ActionResult Create(Role role)
 72         {
 73             mg.Insert(role);
 74             return Content("<script>alert(\'success!\');window.location=\'/Role/Create\';</script>");
 75         }
 76 
 77         [HttpGet]
 78         public ActionResult Modify()
 79         {
 80             RoleVM rolevm = new RoleVM { Roles = mg.QueryAll() };
 81             return View(rolevm);
 82         }
 83 
 84         [HttpPost]
 85         public ActionResult Modify(Role role, FormCollection form)
 86         {
 87             role.Id = ObjectId.Parse(form["id"]);
 88             mg.Update(role);
 89             return Content("<script>alert(\'success!\');window.location=\'/Role/Modify\';</script>");
 90         }
 91 
 92         [HttpPost]
 93         public string Delete(string id)
 94         {
 95             mg.Modify(id, "State", "n");
 96             return "success!";
 97         }
 98     }
 99 
100     public partial class UserController : BaseController
101     {
102         MgHelper<User> mg = new MgHelper<User>();
103 
104         public ActionResult Index()
105         {
106             return View();
107         }
108 
109         [HttpGet]
110         public ActionResult Create()
111         {
112             return View();
113         }
114 
115         [HttpPost]
116         public ActionResult Create(User user)
117         {
118             mg.Insert(user);
119             return Content("<script>alert(\'success!\');window.location=\'/User/Create\';</script>");
120         }
121 
122         [HttpGet]
123         public ActionResult Modify()
124         {
125             UserVM uservm = new UserVM { Users = mg.QueryAll() };
126             return View(uservm);
127         }
128 
129         [HttpPost]
130         public ActionResult Modify(User user, FormCollection form)
131         {
132             user.Id = ObjectId.Parse(form["id"]);
133             mg.Update(user);
134             return Content("<script>alert(\'success!\');window.location=\'/User/Modify\';</script>");
135         }
136 
137         [HttpPost]
138         public string Delete(string id)
139         {
140             mg.Modify(id, "State", "n");
141             return "success!";
142         }
143     }
144 }


我的测试项目是用户管理系统,有三个类: User(用户),Role(角色),Auth(权限)。

 

源代码下载:http://download.csdn.net/detail/cycong108/9737751

 

以上是关于C# mongodb帮助类的主要内容,如果未能解决你的问题,请参考以下文章

如何将代码片段存储在 mongodb 中?

如何通过单击片段内的线性布局从片段类开始新活动?下面是我的代码,但这不起作用

C# 最有用的(自定义)代码片段是啥? [关闭]

c#代码片段快速构建代码

此 Canon SDK C++ 代码片段的等效 C# 代码是啥?

无法从 MongoDB.Driver for C# 访问 MongoCollection 类