C# 更加优质的操作MongoDB数据库

C# 更加优质的操作MongoDB数据库

之前就写过一篇C#操作MongoDB数据库的文章,直接对数据库进行操作,不是很优化,代码在实际项目中比较零散,没有一个统一的规划,所以有了这篇文章,如果要入门的化看看之前的文章也可以进行项目的开发了C# 操作Mongodb数据库

  • 因为我们要进行mongodb数据库的操作,但我们业务层面不想直接跟数据库打交道,所以做了一个中间层ORM(代理映射) 下面我们开始实现这个ORM 步骤如下
  • 还是使用之前的库 MongoDB.Driver

目录结构

在这里插入图片描述
分别解释一下:

  • 真正的中间层是ORM文件夹下的3个文件,而DB文件夹下的Person是测试文件!
  • DBEntity.cs 这是MongoDB的所有的表中的实体的基类~我们自定义的实体类都要集成于DBEntity,例如Person类
  • Proxy.cs 这是一个代理类,任何一个具体的Table类都有一个对应的Proxy代理类
  • Table.cs 这是一个表,说白了,我们业务层面只用接触这个Table类即可,通过Table类进行增删改查!

DBEntity.cs 完整代码

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using System;

namespace Common.ORM
{
    
    
    [Serializable]
    [BsonIgnoreExtraElements(Inherited = true)]
    public abstract class DBEntity
    {
    
    
        public DBEntity()
        {
    
    
            ID = ObjectId.GenerateNewId().ToString();  
        }

        [BsonElement("_id")]
        [BsonRepresentation(BsonType.ObjectId)]  
        public virtual string ID {
    
     get; set; }
    }
}

Proxy.cs 完整代码

using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;

namespace Common.ORM
{
    
    
    public static class Proxy<T>
    {
    
    
        /// <summary>
        /// 数据库表的名字
        /// </summary>
        private static string tableName;

        /// <summary>
        /// 数据库名字
        /// </summary>
        private static string dataBaseName;

        /// <summary>
        /// 数据库连接配置Url
        /// </summary>
        private static string mongoUrl;

        /// <summary>
        /// 数据库单个表的引用(即mongo的单个集合)
        /// </summary>
        private static IMongoCollection<T> collection;

        /// <summary>
        /// 数据库单个表的引用(即mongo的单个集合)
        /// </summary>
        public static IMongoCollection<T> Collection
        {
    
    
            get => collection;
        }

        /// <summary>
        /// 静态构造函数 (注意:不允许出现访问控制符)
        /// </summary>
        static Proxy()
        {
    
    
            Init();
        }

        /// <summary>
        /// 单个表的初始化函数
        /// </summary>
        private static void Init()
        {
    
    
            dataBaseName = "TestMongoDB";

            mongoUrl = "mongodb://localhost:27017";

            tableName = typeof(T).Name;

            BsonClassMap.RegisterClassMap<T>(cm => cm.AutoMap());

            collection = new MongoClient(mongoUrl).GetDatabase(dataBaseName).GetCollection<T>(tableName);
        }
    }
}

Table.cs 完整代码

using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;

namespace Common.ORM
{
    
    
    public class Table<T> where T : DBEntity
    {
    
    
        /// <summary>
        /// 对应的集合的引用
        /// </summary>
        private IMongoCollection<T> collection = Proxy<T>.Collection;

        /// <summary>
        /// 增加一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Add(T entity)
        {
    
    
            try
            {
    
    
                collection.InsertOne(entity);

                return true;
            }
            catch (Exception ex)
            {
    
    
                throw ex;
            }
        }

        /// <summary>
        /// 删除一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public bool Delete(T entity, Expression<Func<T, bool>> conditions = null)
        {
    
    
            try
            {
    
    
                string _id = string.Empty;

                if (conditions == null)
                {
    
    
                    foreach (PropertyInfo item in entity.GetType().GetProperties())
                    {
    
    
                        if (item.Name == "ID" && item.GetValue(entity) != null)
                        {
    
    
                            _id = item.GetValue(entity).ToString();

                            DeleteResult result = collection.DeleteOne(new BsonDocument("_id", BsonValue.Create(new ObjectId(_id))));
                            
                            return result.IsAcknowledged;
                        }
                    }
                }

                DeleteResult res = collection.DeleteOne(conditions);

                return res.IsAcknowledged;
            }
            catch (Exception ex)
            {
    
    
                throw ex;
            }
        }

        /// <summary>
        /// 更新一条记录
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public bool Update(T entity, Expression<Func<T, bool>> conditions = null)
        {
    
    
            try
            {
    
    
                ObjectId _id;

                var options = new ReplaceOptions() {
    
     IsUpsert = true };

                if (conditions == null)
                {
    
    
                    foreach (var item in entity.GetType().GetProperties())
                    {
    
    
                        if (item.Name == "ID" && item.GetValue(entity) != null)
                        {
    
    
                            _id = new ObjectId(item.GetValue(entity).ToString());

                            ReplaceOneResult result = collection.ReplaceOne(new BsonDocument("_id", BsonValue.Create(_id)), entity, options);
                            
                            return result.IsAcknowledged;
                        }
                    }
                }

                ReplaceOneResult res = collection.ReplaceOne(conditions, entity, options);

                return res.IsAcknowledged;
            }
            catch (Exception ex)
            {
    
    
                throw ex;
            }
        }

        /// <summary>
        /// 查找一条记录
        /// </summary>
        /// <param name="conditions"></param>
        /// <returns></returns>
        public List<T> Find(Expression<Func<T, bool>> conditions = null)
        {
    
    
            try
            {
    
    
                if (conditions == null)
                {
    
    
                    conditions = t => true;
                }

                return collection.Find(conditions).ToList() ?? new List<T>();
            }
            catch (Exception ex)
            {
    
    
                throw ex;
            }
        }
    }
}

Person.cs 完整代码

using Common.ORM;
using MongoDB.Bson.Serialization.Attributes;
using System;
using System.Collections.Generic;

namespace Common.DB
{
    
    
    [Serializable]
    public class Person : DBEntity
    {
    
    
        [BsonConstructor]
        public Person(string name, int age, string guid, GenderEnum gender)
        {
    
    
            Name = name;

            Age = age;

            Guid = guid;

            Gender = gender;
        }

        public override string ToString()
        {
    
    
            return "ID:" + ID + "  " + "user:" + Name + "  " + "age:" + Age + "  " + "guid:" + Guid + "  " + "Gender:" + Gender.ToString() + "  " + "宠物叫" + Pet.Name + "," + Pet.Age + "岁了";
        }

        public string Name {
    
     get; set; }

        public int Age {
    
     get; set; }

        public string Guid {
    
     get; set; }

        public GenderEnum Gender {
    
     get; set; }

        public List<Person> Students {
    
     get => students; set => students = value; }

        public Pet Pet {
    
     get => pet; set => pet = value; }

        private Pet pet;

        private List<Person> students;
    }

    public enum GenderEnum
    {
    
    ,}

    public class Pet
    {
    
    
        public string Name {
    
     get => name; set => name = value; }

        public int Age {
    
     get => age; set => age = value; }

        private string name;

        private int age;
    }
}

测试

ORM的框架部分以上就整理完了,下面我们来使用它!

        private static void TestDB()
        {
    
    
            Person person = new Person("张三", 8, Guid.NewGuid().ToString(), GenderEnum.);
            
            person.Students = new List<Person>() 
            {
    
     
                new Person("张小三1", 8, Guid.NewGuid().ToString(), GenderEnum.),

                new Person("张小三2", 8, Guid.NewGuid().ToString(), GenderEnum.),

                new Person("张小三3", 8, Guid.NewGuid().ToString(), GenderEnum.),

                new Person("张小三4", 8, Guid.NewGuid().ToString(), GenderEnum.)
            };

            person.Pet = new Pet() {
    
     Name = "旺财", Age = 3 };

            personDB.Add(person);
        }

请添加图片描述

猜你喜欢

转载自blog.csdn.net/zzzsss123333/article/details/125597530