当前位置:网站首页>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);
}
边栏推荐
- 欧拉函数
- Lenovo explains in detail the green smart city digital twin platform for the first time to solve the difficulties of urban dual carbon upgrading
- Small hair cat Internet of things platform construction and application model
- 2022 Health Exhibition, Beijing Health Expo, China Health Exhibition, great health exhibition November 13
- Data set division
- HMM隐马尔可夫模型最详细讲解与代码实现
- kotlin 基本使用
- Kotlin cycle control
- Introduction to ACM combination counting
- Template_ Judging prime_ Square root / six prime method
猜你喜欢
Swagger suddenly went crazy
Crystal optoelectronics: ar-hud products of Chang'an dark blue sl03 are supplied by the company
JVM系列之对象的创建
c# . Net MVC uses Baidu ueditor rich text box to upload files (pictures, videos, etc.)
What is the application technology of neural network and Internet of things
做社交媒体营销应该注意些什么?Shopline卖家的成功秘笈在这里!
BCG 使用之新建向导效果
华为nova 10系列支持应用安全检测功能 筑牢手机安全防火墙
New wizard effect used by BCG
In the first month of its launch, the tourist praise rate of this campsite was as high as 99.9%! How did he do it?
随机推荐
Lenovo explains in detail the green smart city digital twin platform for the first time to solve the difficulties of urban dual carbon upgrading
TCP两次挥手,你见过吗?那四次握手呢?
双冒号作用运算符以及命名空间详解
[graduation season] green ant new fermented grains wine, red mud small stove. If it snows late, can you drink a cup?
牛客小白月赛7 E Applese的超能力
Educational codeforces round 22 E. Army Creation
1006 sign in and sign out (25 points) (PAT class a)
Actual combat simulation │ JWT login authentication
HDU 1097 A hard puzzle
Master the use of auto analyze in data warehouse
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 使用之CBCGPProgressDlgCtrl進度條使用
凌云出海记 | 文华在线&华为云:打造非洲智慧教学新方案
Actual combat simulation │ JWT login authentication
Prometheus installation
Utilisation de la barre de progression cbcggprogressdlgctrl utilisée par BCG
YOLOv5s-ShuffleNetV2
Regular replacement [JS, regular expression]
Template_ Large integer subtraction_ Regardless of size
Neural network IOT platform construction (IOT platform construction practical tutorial)