当前位置:网站首页>C # better operation mongodb database
C # better operation mongodb database
2022-07-04 20:10:00 【Handsome_ shuai_】
C# Better operation MongoDB database
I wrote an article before C# operation MongoDB Database articles , Operate the database directly , Not very optimized , The code is scattered in the actual project , There is no unified plan , So with this article , If you want to get started, you can also develop the project by looking at the previous articles C# operation Mongodb database
- Because we're going to mongodb Operation of database , But our business level doesn't want to deal directly with the database , So we made an intermediate layer ORM( Proxy mapping ) Now let's start to realize this ORM Steps are as follows
- Still use the previous Library
MongoDB.Driver
Directory structure
Explain separately :
- The real middle tier is ORM Under folder 3 File , and DB Under folder Person This is a test file !
- DBEntity.cs This is a MongoDB The base class of all entities in the table ~ Our customized entity classes should be integrated into DBEntity, for example Person class
- Proxy.cs This is a proxy class , Any specific Table Classes have a corresponding Proxy proxy class
- Table.cs This is a watch , To put it bluntly , Our business level only contacts this Table The class can , adopt Table Class to add, delete, and modify !
DBEntity.cs Complete code
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 Complete code
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;
namespace Common.ORM
{
public static class Proxy<T>
{
/// <summary>
/// Name of the database table
/// </summary>
private static string tableName;
/// <summary>
/// Database name
/// </summary>
private static string dataBaseName;
/// <summary>
/// Database connection configuration Url
/// </summary>
private static string mongoUrl;
/// <summary>
/// Reference to a single table in the database ( namely mongo A single set of )
/// </summary>
private static IMongoCollection<T> collection;
/// <summary>
/// Reference to a single table in the database ( namely mongo A single set of )
/// </summary>
public static IMongoCollection<T> Collection
{
get => collection;
}
/// <summary>
/// Static constructor ( Be careful : Access control characters are not allowed )
/// </summary>
static Proxy()
{
Init();
}
/// <summary>
/// Initialization function of a single table
/// </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 Complete code
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>
/// The reference of the corresponding set
/// </summary>
private IMongoCollection<T> collection = Proxy<T>.Collection;
/// <summary>
/// Add a record
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Add(T entity)
{
try
{
collection.InsertOne(entity);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Delete a record
/// </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>
/// Update a record
/// </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>
/// Find a record
/// </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 Complete code
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 call " + Pet.Name + "," + Pet.Age + " Year old ";
}
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
{
male ,
Woman
}
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;
}
}
test
ORM The above part of the framework is finished , Now let's use it !
private static void TestDB()
{
Person person = new Person(" Zhang San ", 8, Guid.NewGuid().ToString(), GenderEnum. male );
person.Students = new List<Person>()
{
new Person(" Zhang Xiaosan 1", 8, Guid.NewGuid().ToString(), GenderEnum. male ),
new Person(" Zhang Xiaosan 2", 8, Guid.NewGuid().ToString(), GenderEnum. male ),
new Person(" Zhang Xiaosan 3", 8, Guid.NewGuid().ToString(), GenderEnum. male ),
new Person(" Zhang Xiaosan 4", 8, Guid.NewGuid().ToString(), GenderEnum. male )
};
person.Pet = new Pet() {
Name = " Wangcai ", Age = 3 };
personDB.Add(person);
}
边栏推荐
- TCP waves twice, have you seen it? What about four handshakes?
- 1005 Spell It Right(20 分)(PAT甲级)
- Educational codeforces round 22 E. Army Creation
- BCG 使用之CBCGPProgressDlgCtrl進度條使用
- Dark horse programmer - software testing - stage 08 2-linux and database-23-30-process port related, modify file permissions, obtain port number information, program and process related operations, Li
- ACM组合计数入门
- 有关架构设计的个人思考(本文后续不断修改更新)
- kotlin 条件控制
- Matrix flip (array simulation)
- 1003 emergency (25 points) (PAT class a)
猜你喜欢
Regular replacement [JS, regular expression]
线上数据库迁移的几种方法
多表操作-内连接查询
CANN算子:利用迭代器高效实现Tensor数据切割分块处理
C语言-入门-基础-语法-流程控制(七)
The explain statement in MySQL queries whether SQL is indexed, and several types in extra collate and summarize
Detailed explanation of Audi EDI invoice message
JVM系列之对象的创建
Lenovo explains in detail the green smart city digital twin platform for the first time to solve the difficulties of urban dual carbon upgrading
实战模拟│JWT 登录认证
随机推荐
Utilisation de la barre de progression cbcggprogressdlgctrl utilisée par BCG
Neural network IOT platform construction (IOT platform construction practical tutorial)
Double colon function operator and namespace explanation
YOLOv5s-ShuffleNetV2
2022 version of stronger jsonpath compatibility and performance test (snack3, fastjson2, jayway.jsonpath)
Find the nth power of 2
记一次 .NET 某工控数据采集平台 线程数 爆高分析
HMM隐马尔可夫模型最详细讲解与代码实现
ACM组合计数入门
Small hair cat Internet of things platform construction and application model
BCG 使用之CBCGPProgressDlgCtrl进度条使用
Abc229 summary (connected component count of the longest continuous character graph in the interval)
What is the application technology of neural network and Internet of things
实战模拟│JWT 登录认证
BCG 使用之CBCGPProgressDlgCtrl進度條使用
English语法_名词 - 使用
Detailed explanation of Audi EDI invoice message
Dark horse programmer - software testing - stage 08 2-linux and database-23-30-process port related, modify file permissions, obtain port number information, program and process related operations, Li
Pytoch learning (4)
Chrome开发工具:VMxxx文件是什么鬼