当前位置:网站首页>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);
}
边栏推荐
- HDU 6440 2018中国大学生程序设计网络选拔赛
- The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
- TCP waves twice, have you seen it? What about four handshakes?
- Specify the character set to output
- YOLOv5s-ShuffleNetV2
- Basic use of kotlin
- 做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
- C language - Introduction - Foundation - grammar - process control (VII)
- Educational codeforces round 22 E. Army Creation
- Mysql database basic operation -ddl | dark horse programmer
猜你喜欢
How is the entered query SQL statement executed?
Huawei Nova 10 series supports the application security detection function to build a strong mobile security firewall
Cann operator: using iterators to efficiently realize tensor data cutting and blocking processing
欧拉函数
Wireshark network packet capture
BCG 使用之新建向导效果
上线首月,这家露营地游客好评率高达99.9%!他是怎么做到的?
Siemens HMI download prompts lack of panel image solution
92.(cesium篇)cesium楼栋分层
Pointnext: review pointnet through improved model training and scaling strategies++
随机推荐
Process of manually encrypt the mass-producing firmware and programming ESP devices
黑马程序员-软件测试--07阶段2-linux和数据库-09-24-linux命令学习步骤,通配符,绝对路径,相对路径,文件和目录常用命令,文件内容相关操作,查看日志文件,ping命令使用,
c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
JVM系列之对象的创建
Chrome development tool: what the hell is vmxxx file
BCG 使用之CBCGPProgressDlg进度条使用
Pytoch learning (4)
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
Siemens HMI download prompts lack of panel image solution
ACM组合计数入门
HDU 6440 2018中国大学生程序设计网络选拔赛
Informatics Olympiad 1336: [example 3-1] find roots and children
Multi table operation - external connection query
1006 sign in and sign out (25 points) (PAT class a)
HDU 6440 2018 Chinese college student program design network competition
1003 emergency (25 points) (PAT class a)
Stream stream
"Only one trip", active recommendation and exploration of community installation and maintenance tasks
BCG 使用之CBCGPProgressDlgCtrl進度條使用
Lenovo explains in detail the green smart city digital twin platform for the first time to solve the difficulties of urban dual carbon upgrading