之前就写过一篇C#操作MongoDB数据库的文章,直接对数据库进行操作,不是很优化,代码在实际项目中比较零散,没有一个统一的规划,所以有了这篇文章,如果要入门的化看看之前的文章也可以进行项目的开发了C# 操作Mongodb数据库
MongoDB.Driver
分别解释一下:
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; }
}
}
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System;
namespace Common.ORM
{
public static class Proxy<T>
{
/// <summary>
/// 数据库表的名字
/// </summary>
private static string tableName;
/// <summary>
/// 数据库名字
/// </summary>
private static string dataBaseName;
/// <summary>
/// 数据库连接配置Url
/// </summary>
private static string mongoUrl;
/// <summary>
/// 数据库单个表的引用(即mongo的单个集合)
/// </summary>
private static IMongoCollection<T> collection;
/// <summary>
/// 数据库单个表的引用(即mongo的单个集合)
/// </summary>
public static IMongoCollection<T> Collection
{
get => collection;
}
/// <summary>
/// 静态构造函数 (注意:不允许出现访问控制符)
/// </summary>
static Proxy()
{
Init();
}
/// <summary>
/// 单个表的初始化函数
/// </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);
}
}
}
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>
/// 对应的集合的引用
/// </summary>
private IMongoCollection<T> collection = Proxy<T>.Collection;
/// <summary>
/// 增加一条记录
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool Add(T entity)
{
try
{
collection.InsertOne(entity);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// 删除一条记录
/// </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>
/// 更新一条记录
/// </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>
/// 查找一条记录
/// </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;
}
}
}
}
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.Name + "," + Pet.Age + "岁了";
}
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
{
男,
女
}
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;
}
}
ORM的框架部分以上就整理完了,下面我们来使用它!
private static void TestDB()
{
Person person = new Person("张三", 8, Guid.NewGuid().ToString(), GenderEnum.男);
person.Students = new List<Person>()
{
new Person("张小三1", 8, Guid.NewGuid().ToString(), GenderEnum.男),
new Person("张小三2", 8, Guid.NewGuid().ToString(), GenderEnum.男),
new Person("张小三3", 8, Guid.NewGuid().ToString(), GenderEnum.男),
new Person("张小三4", 8, Guid.NewGuid().ToString(), GenderEnum.男)
};
person.Pet = new Pet() { Name = "旺财", Age = 3 };
personDB.Add(person);
}