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

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

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

 <appSettings>
<add key="webpages:Version" value="3.0.0.0"/>
<add key="webpages:Enabled" value="false"/>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
<add key="dbName" value="demodb"/>
</appSettings>
<connectionStrings>
<add name="connStr" connectionString="mongodb://127.0.0.1:27017"/>
</connectionStrings>

MongoDbHelper类:

 using Cong.Model;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq; namespace Cong.Utility
{
public class Db
{
private static readonly string connStr = ConfigurationManager.ConnectionStrings["connStr"].ToString(); private static readonly string dbName = ConfigurationManager.AppSettings["dbName"].ToString(); private static IMongoDatabase db = null; private static readonly object lockHelper = new object(); private Db() { } public static IMongoDatabase GetDb()
{
if (db == null)
{
lock (lockHelper)
{
if (db == null)
{
var client = new MongoClient(connStr);
db = client.GetDatabase(dbName);
}
}
}
return db;
}
} public class MongoDbHelper<T> where T : BaseEntity
{
private IMongoDatabase db = null; private IMongoCollection<T> collection = null; public MgHelper()
{
this.db = Db.GetDb();
collection = db.GetCollection<T>(typeof(T).Name);
} public T Insert(T entity)
{
var flag = ObjectId.GenerateNewId();
entity.GetType().GetProperty("Id").SetValue(entity, flag);
entity.State = "y";
entity.CreateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
entity.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); collection.InsertOneAsync(entity);
return entity;
} public void Modify(string id, string field, string value)
{
var filter = Builders<T>.Filter.Eq("Id", ObjectId.Parse(id));
var updated = Builders<T>.Update.Set(field, value);
UpdateResult result = collection.UpdateOneAsync(filter, updated).Result;
} public void Update(T entity)
{
var old = collection.Find(e => e.Id.Equals(entity.Id)).ToList().FirstOrDefault(); foreach (var prop in entity.GetType().GetProperties())
{
var newValue = prop.GetValue(entity);
var oldValue = old.GetType().GetProperty(prop.Name).GetValue(old);
if (newValue != null)
{
if (!newValue.ToString().Equals(oldValue.ToString()))
{
old.GetType().GetProperty(prop.Name).SetValue(old, newValue.ToString());
}
}
}
old.State = "y";
old.UpdateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); var filter = Builders<T>.Filter.Eq("Id", entity.Id);
ReplaceOneResult result = collection.ReplaceOneAsync(filter, old).Result;
} public void Delete(T entity)
{
var filter = Builders<T>.Filter.Eq("Id", entity.Id);
collection.DeleteOneAsync(filter);
} public T QueryOne(string id)
{
return collection.Find(a => a.Id == ObjectId.Parse(id)).ToList().FirstOrDefault();
} public List<T> QueryAll()
{
return collection.Find(a => a.State.Equals("y")).ToList();
}
}
}

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

BaseEntity:

 using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Cong.Model
{
public abstract class BaseEntity
{
public ObjectId Id { get; set; } public string State { get; set; } public string CreateTime { get; set; } public string UpdateTime { get; set; }
}
}

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

 using Cong.Model;
using Cong.Utility;
using MongoDB.Bson;
using System.Web.Mvc;
using WebApp.Models; namespace WebApp.Controllers
{ public partial class AuthController : BaseController
{
MgHelper<Auth> mg = new MgHelper<Auth>(); public ActionResult Index()
{
return View();
} [HttpGet]
public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(Auth auth)
{
mg.Insert(auth);
return Content("<script>alert('success!');window.location='/Auth/Create';</script>");
} [HttpGet]
public ActionResult Modify()
{
AuthVM authvm = new AuthVM { Auths = mg.QueryAll() };
return View(authvm);
} [HttpPost]
public ActionResult Modify(Auth auth, FormCollection form)
{
auth.Id = ObjectId.Parse(form["id"]);
mg.Update(auth);
return Content("<script>alert('success!');window.location='/Auth/Modify';</script>");
} [HttpPost]
public string Delete(string id)
{
mg.Modify(id, "State", "n");
return "success!";
}
} public partial class RoleController : BaseController
{
MgHelper<Role> mg = new MgHelper<Role>(); public ActionResult Index()
{
return View();
} [HttpGet]
public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(Role role)
{
mg.Insert(role);
return Content("<script>alert('success!');window.location='/Role/Create';</script>");
} [HttpGet]
public ActionResult Modify()
{
RoleVM rolevm = new RoleVM { Roles = mg.QueryAll() };
return View(rolevm);
} [HttpPost]
public ActionResult Modify(Role role, FormCollection form)
{
role.Id = ObjectId.Parse(form["id"]);
mg.Update(role);
return Content("<script>alert('success!');window.location='/Role/Modify';</script>");
} [HttpPost]
public string Delete(string id)
{
mg.Modify(id, "State", "n");
return "success!";
}
} public partial class UserController : BaseController
{
MgHelper<User> mg = new MgHelper<User>(); public ActionResult Index()
{
return View();
} [HttpGet]
public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(User user)
{
mg.Insert(user);
return Content("<script>alert('success!');window.location='/User/Create';</script>");
} [HttpGet]
public ActionResult Modify()
{
UserVM uservm = new UserVM { Users = mg.QueryAll() };
return View(uservm);
} [HttpPost]
public ActionResult Modify(User user, FormCollection form)
{
user.Id = ObjectId.Parse(form["id"]);
mg.Update(user);
return Content("<script>alert('success!');window.location='/User/Modify';</script>");
} [HttpPost]
public string Delete(string id)
{
mg.Modify(id, "State", "n");
return "success!";
}
}
}

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

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

最新文章

  1. HTML学习笔记——标签(二)
  2. Oracle普通表-&gt;分区表转换(9亿数据量)
  3. 20145220&amp;20145209&amp;20145309信息安全系统设计基础实验报告(5)
  4. NFC(12)使用Android Beam技术传输文本数据及它是什么
  5. HDU 1503 Advanced Fruits (LCS,变形)
  6. AsyncTask 解析
  7. cpu95%,查找问题sql
  8. Comparing the contribution of NBA draft picks(转)
  9. springmvc 之 Controller
  10. Java 后端微信支付demo
  11. 依赖注入[2]: 基于IoC的设计模式
  12. [三]java8 函数式编程Stream 概念深入理解 Stream 运行原理 Stream设计思路
  13. Create Maximum Number
  14. 【JSP】JSP的介绍和基本原理
  15. JS-构造函数2
  16. pycharm 模板添加作者时间信息
  17. SpringMVC之学习(1)
  18. ActionMQ5.8.0 JMS实例 手把手详细图解
  19. 白盒测试实践项目(day4)
  20. mongodb数据导入导出mongoexport/mongoimport

热门文章

  1. boost::asio与ACE的对比
  2. leetcode 链表 Partition List
  3. vim 常用插件功能跟配置
  4. Onvif开发之客户端鉴权获取参数篇
  5. 缓存函数memorize
  6. html页面中块级元素的居中
  7. Javascript和jquery事件--事件冒泡和事件捕获
  8. LuoguP4016 负载平衡问题(费用流)
  9. docker的数据持久化
  10. factor---将素数分解为质数