当前位置:网站首页>C# 更加优质的操作MongoDB数据库
C# 更加优质的操作MongoDB数据库
2022-07-04 15:08:00 【帅_shuai_】
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);
}

边栏推荐
- tp配置多数据库
- Accounting regulations and professional ethics [9]
- 基于wifi控制的51单片机温度报警器
- World Environment Day | Chow Tai Fook serves wholeheartedly to promote carbon reduction and environmental protection
- Overflow: the combination of auto and Felx
- overflow:auto与felx结合的用法
- Market trend report, technical innovation and market forecast of tetrabromophthalate (pht4 diol) in China
- Maximum subarray and matrix multiplication
- Opencv learning -- arithmetic operation of image of basic operation
- Research Report on market supply and demand and strategy of China's four sided flat bag industry
猜你喜欢

Communication mode based on stm32f1 single chip microcomputer

Interface fonctionnelle, référence de méthode, Widget de tri de liste implémenté par lambda

D3D11_ Chili_ Tutorial (2): draw a triangle

I let the database lock the table! Almost fired!

多年锤炼,迈向Kata 3.0 !走进开箱即用的安全容器体验之旅| 龙蜥技术

对人胜率84%,DeepMind AI首次在西洋陆军棋中达到人类专家水平

Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology

Yanwen logistics plans to be listed on Shenzhen Stock Exchange: it is mainly engaged in international express business, and its gross profit margin is far lower than the industry level

What is torch NN?

GO开发:如何利用Go单例模式保障流媒体高并发的安全性?
随机推荐
Years of training, towards Kata 3.0! Enter the safe container experience out of the box | dragon lizard Technology
Interface fonctionnelle, référence de méthode, Widget de tri de liste implémenté par lambda
一图看懂ThreadLocal
Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
GO开发:如何利用Go单例模式保障流媒体高并发的安全性?
Go language loop statement (under Lesson 10)
How to "use" Perl modules in directories that are not in @inc- How do I 'use' a Perl module in a directory not in @INC?
Hash table
时钟轮在 RPC 中的应用
Overflow: the combination of auto and Felx
DIY a low-cost multi-functional dot matrix clock!
矿产行业商业供应链协同系统解决方案:构建数智化供应链平台,保障矿产资源安全供应
中位数与次序统计量
How to contribute to the source code of ongdb core project
Research Report on market supply and demand and strategy of China's well completion equipment industry
高度剩余法
Detailed process of DC-2 range construction and penetration practice (DC range Series)
Accounting regulations and professional ethics [8]
智慧物流園區供應鏈管理系統解决方案:數智化供應鏈賦能物流運輸行業供應鏈新模式
Filtered off site request to