.net Framework使用之 MongoDB

新建Helper

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace WebApplication1.net
{
    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 : Users
    {
        private IMongoDatabase db = null;

        private IMongoCollection<T> collection = null;

        public MongoDbHelper()
        {
            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();
        }
    }
}

web.config加入配置

新建类

using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.net
{
    public abstract class BaseEntity
    {
        public ObjectId Id { get; set; }

        public string State { get; set; }

        public string CreateTime { get; set; }

        public string UpdateTime { get; set; }
    }
}
using MongoDB.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.net
{
    public class Users:BaseEntity
    {
        public int UsersId { get; set; }

        public string Name { get; set; }

    }
}

使用

  public ActionResult Test()
        {
            Users user = new Users();
            user.UsersId = 1;
            user.Name = "张三";
            //新增
           var a= mg.Insert(user);
            //查询
          var b=  mg.QueryAll();
           //var c= mg.QueryOne(1.ToString());
            //修改
            user.Name = "张三123";
            mg.Update(user);

            var b2 = mg.QueryAll();


            //删除
            mg.Delete(user);

            var b3 = mg.QueryAll();
            return View();
        }

 

转载于:https://www.cnblogs.com/LiChen19951127/p/10650369.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值