这是在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

C# mongodb帮助类的更多相关文章

  1. JAVA单例MongoDB工具类

    我经常对MongoDB进行一些基础操作,将这些常用操作合并到一个工具类中,方便自己开发使用. 没用Spring Data.Morphia等框架是为了减少学习.维护成本,另外自己直接JDBC方式的话可以 ...

  2. mongodb工具类

    pom.xml文件增加Mongodb jar包 <dependency> <groupId>org.mongodb</groupId> <artifactId ...

  3. 【clickhouse专栏】对标mongodb存储类JSON数据文档统计分析

    一.文档存储的需求 很多的开发者都使用过mongodb,在mongodb中数据记录是以文档的形式存在的(类似于一种多级嵌套SQL的形式).比如下面的JSON数据结构:dev_ip表示某一台服务器的ip ...

  4. mongodb 操作类

    在使用这个类之前,建议先自己去写,把方法都了解了再用,这样你就可以在适当的时候修个此类,另外请自己构建PagerInfo using System; using System.Collections. ...

  5. mongoDB工具类以及测试类【java】

    java操作mongo工具类 package Utils; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; im ...

  6. mongodb基类封装实例

    mongodb的基类 1 <?php 2 3 namespace BI\Service\MongoDB; 4 5 use MongoDB\Driver\BulkWrite; 6 use Mong ...

  7. 推荐一个php7+ mongodb三方类

      373 次阅读  ·  读完需要 8 分钟 5 由于项目需要,把项目升级到了php7.但是升级了之后发现mongo扩展不能用了.php7.0以上只支持mongodb扩展了.而mongodb扩展的驱 ...

  8. 基于C#在Mongodb的Skip-Limit和Where-Limit的分页对比 并且含mongodb帮助类的源码

    最近在设计的日志服务中需要用到Mongodb这个Nosql数据库(不知道Mongodb的点我),由于是用于纯存日志,而且日志量巨大,百万千万级的,所以需要用到它的分页查询. 不过LZ也是刚刚接触这个数 ...

  9. 【经验分享】Mongodb操作类实现CRUD

    一.背景 公司项目中在做数据存储时使用到Mongodb,所以想着将Mongodb的操作封装后可供项目中其他成员方便使用. 附上Mongodb的下载地址: 下载 1.Mongodb类 此类主要是用来构造 ...

随机推荐

  1. 解决树莓派新版系统 ssh连接不了问题

    一.解决办法 由于有连接了显示器,所以可以直接输入命令行开启树莓派的SSH,并且使用putty连接就可以. sudo service ssh start sudo service ssh sttus ...

  2. 免费css布局和模板集合

    Internet 上有很多基于 (X)HTML/CSS 标记的模板.如果你是一个 Web 开发人员,你不希望把时间一次又一次地浪费在重复代码设计上面,这里提供了一个列表,提供了基于 CSS 的免费模板 ...

  3. Oracle的表空间和sqlplus

    1.  表空间的概念 曾经接触过的数据库都没有听到过表空间这个词,在前一段时间看到Oracle数据库的时候发现表空间无处不在. 所以表空间在Oracle数据库中应该是一个非经常常使用而且非常重要的概念 ...

  4. [UnityUI]循环滑动列表

    效果图: 使用的是UGUI和DOTween 当中比較关键的是循环滑动和层次排序: 1.循环滑动:这里先如果显示五张图片.分别标记为0,1,2,3,4,那么当向左滑动时,序列就变为1,2,3,4,0,这 ...

  5. ubuntu-删除内核

    今天进入公司第一天,公司需要给电脑安装ubuntu,这个是由it部门帮忙安装的.但是,我不小心升级了内核版本,接下来就悲剧了,因为内核版本升级以后,直接导致了环境错误,很多公司内部使用的工具都不能用了 ...

  6. .Net 自动属性结合手动属性

    Model using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ...

  7. Android 给图片 加边框

    图片处理时,有时需要为图片加一些边框,下面介绍一种为图片添加简单边框的方法. 基本思路是:将边框图片裁剪成八张小图片(图片大小最好一致,不然后面处理会很麻烦),分别对应左上角,左边,左下角,下边,右下 ...

  8. windows下gopath设置

    下载了go语言的安装包, 然后安装, 装完了需要设置三个地方: 1. 在windows的PATH变量中添加go的可执行文件所在的目录: PATH=C:\Go\bin;其他设置; 2. 设置 GOROO ...

  9. 「HAOI2018」字串覆盖

    「HAOI2018」字串覆盖 题意: ​ 给你两个字符串,长度都为\(N\),以及一个参数\(K\),有\(M\)个询问,每次给你一个\(B\)串的一个子串,问用这个字串去覆盖\(A\)串一段区间的最 ...

  10. JavaScript学习总结(11)——JS常用函数(二)

    37. getElementsByClassName ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 function getElementsByClassName( ...