当前位置:网站首页>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);
}
边栏推荐
- "Cannot initialize Photoshop because the temporary storage disk is full" graphic solution
- Use and principle of thread pool
- Maximum subarray and matrix multiplication
- Oracle监听器Server端与Client端配置实例
- Hash table
- 一图看懂ThreadLocal
- Research Report on market supply and demand and strategy of surgical stapler industry in China
- Market trend report, technical innovation and market forecast of China's hair repair therapeutic apparatus
- Principle and general steps of SQL injection
- Smart Logistics Park supply chain management system solution: digital intelligent supply chain enables a new supply chain model for the logistics transportation industry
猜你喜欢
Understand asp Net core - Authentication Based on jwtbearer
Software Engineer vs Hardware Engineer
overflow:auto与felx结合的用法
~89 deformation translation
Cut! 39 year old Ali P9, saved 150million
Vscode prompt Please install clang or check configuration 'clang executable‘
Solution du système de gestion de la chaîne d'approvisionnement du parc logistique intelligent
Can you really use MySQL explain?
I let the database lock the table! Almost fired!
Object. Usage of keys()
随机推荐
Object. Usage of keys()
[Chongqing Guangdong education] National Open University spring 2019 1248 public sector human resource management reference questions
Li Kou today's question -1200 Minimum absolute difference
最大子数组与矩阵乘法
Hair and fuzz interceptor Industry Research Report - market status analysis and development prospect forecast
The vscode waveform curve prompts that the header file cannot be found (an error is reported if the header file exists)
NoSQL之readis配置与优化(终章)
Redis: SDS source code analysis
Go development: how to use go singleton mode to ensure the security of high concurrency of streaming media?
egg. JS learning notes
Market trend report, technical innovation and market forecast of taillight components in China
Firebird experience summary
China's roof ladder market trend report, technological innovation and market forecast
Research Report on market supply and demand and strategy of China's Sodium Tetraphenylborate (cas+143-66-8) industry
Communication mode based on stm32f1 single chip microcomputer
《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(2)-初识Fiddler让你理性认识一下
China Indonesia adhesive market trend report, technological innovation and market forecast
Capvision Rongying's prospectus in Hong Kong was "invalid": it was strictly questioned by the CSRC and required supplementary disclosure
Start by counting
矿产行业商业供应链协同系统解决方案:构建数智化供应链平台,保障矿产资源安全供应