当前位置:网站首页>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);
}
边栏推荐
- kotlin 继承
- Some thoughts on whether the judgment point is located in the contour
- kotlin 基本数据类型
- Template_ Large integer subtraction_ Regardless of size
- Allure of pytest visual test report
- Kotlin condition control
- YOLOv5s-ShuffleNetV2
- 1009 product of polynomials (25 points) (PAT class a)
- 2022 Health Exhibition, health exhibition, Beijing Great Health Exhibition and health industry exhibition were held in November
- Swagger突然发癫
猜你喜欢
Mysql database basic operation -ddl | dark horse programmer
水晶光电:长安深蓝SL03的AR-HUD产品由公司供应
Creation of JVM family objects
Neural network IOT platform construction (IOT platform construction practical tutorial)
C # use stopwatch to measure the running time of the program
黑马程序员-软件测试--09阶段2-linux和数据库-31-43修改文件权限字母发的说明,-查找链接修改文件,查找文件命令,链接文件,压缩解压方式,vi编辑器基本使用,
What is the application technology of neural network and Internet of things
Wireshark network packet capture
Swagger suddenly went crazy
What should we pay attention to when doing social media marketing? Here is the success secret of shopline sellers!
随机推荐
Write it down once Net analysis of thread burst height of an industrial control data acquisition platform
PHP pseudo original API docking method
c# .net mvc 使用百度Ueditor富文本框上传文件(图片,视频等)
c# . Net MVC uses Baidu ueditor rich text box to upload files (pictures, videos, etc.)
华为云云商店首页 Banner 资源位申请
kotlin 基本使用
1011 World Cup betting (20 points) (pat a)
The company needs to be monitored. How do ZABBIX and Prometheus choose? That's the right choice!
1009 product of polynomials (25 points) (PAT class a)
Kotlin inheritance
2022 version of stronger jsonpath compatibility and performance test (snack3, fastjson2, jayway.jsonpath)
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,
Online text line fixed length fill tool
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
Cbcgpprogressdlgctrl progress bar used by BCG
Wireshark network packet capture
需求开发思考
Kotlin cycle control
1009 Product of Polynomials(25 分)(PAT甲级)
Chrome开发工具:VMxxx文件是什么鬼