当前位置:网站首页>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);
}
边栏推荐
- 应用实践 | 蜀海供应链基于 Apache Doris 的数据中台建设
- English语法_名词 - 使用
- Kotlin basic data type
- PHP pseudo original API docking method
- English grammar_ Noun - use
- Find the nth power of 2
- Socket programming demo II
- The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
- 1003 emergency (25 points) (PAT class a)
- Cbcgpprogressdlg progress bar used by BCG
猜你喜欢
C# 使用StopWatch测量程序运行时间
YOLOv5s-ShuffleNetV2
Actual combat simulation │ JWT login authentication
Actual combat simulation │ JWT login authentication
Employment prospects and current situation of Internet of things application technology
ACM组合计数入门
Dark horse programmer - software testing - 09 stage 2-linux and database -31-43 instructions issued by modifying the file permission letter, - find the link to modify the file, find the file command,
多表操作-内连接查询
What does the neural network Internet of things mean? Popular explanation
Pointnext: review pointnet through improved model training and scaling strategies++
随机推荐
Kotlin classes and objects
欧拉函数
Niuke Xiaobai month race 7 F question
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
BCG 使用之新建向导效果
Application practice | Shuhai supply chain construction of data center based on Apache Doris
1002. A+b for Polynomials (25) (PAT class a)
Some thoughts on whether the judgment point is located in the contour
Write it down once Net analysis of thread burst height of an industrial control data acquisition platform
Allure of pytest visual test report
1008 elevator (20 points) (PAT class a)
Abc229 summary (connected component count of the longest continuous character graph in the interval)
Euler function
Niuke Xiaobai monthly race 7 I new Microsoft Office Word document
In operation (i.e. included in) usage of SSRs filter
What does the neural network Internet of things mean? Popular explanation
Employment prospects and current situation of Internet of things application technology
华为nova 10系列支持应用安全检测功能 筑牢手机安全防火墙
repeat_ P1002 [NOIP2002 popularization group] cross the river pawn_ dp
BCG 使用之CBCGPProgressDlgCtrl进度条使用