C# 使用mongodb 帮助类

在C#中使用MongoDB,你需要安装MongoDB的C#驱动程序,通常使用MongoDB.Driver。

以下是一个简单的帮助类,用于连接MongoDB数据库并执行基本的CRUD操作。

首先,通过NuGet安装MongoDB.Driver:

Install-Package MongoDB.Driver

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
 
public static class MongoDBHelper<T> where T : class
{
    private static IMongoCollection<T> _collection;
 
    static MongoDBHelper()
    {
        var connectionString = "your_mongodb_connection_string";
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("your_database_name");
        _collection = database.GetCollection<T>("your_collection_name");
    }
 
    public static List<T> GetAll()
    {
        return _collection.Find(new BsonDocument()).ToList();
    }
 
    public static T GetById(string id)
    {
        return _collection.Find(Builders<T>.Filter.Eq("_id", id)).FirstOrDefault();
    }
 
    public static T GetSingle(Expression<Func<T, bool>> predicate)
    {
        return _collection.Find(predicate).FirstOrDefault();
    }
 
    public static void Insert(T entity)
    {
        _collection.InsertOne(entity);
    }
 
    public static void Update(T entity)
    {
        _collection.ReplaceOne(Builders<T>.Filter.Eq("_id", entity.Id), entity);
    }
 
    public static void Delete(string id)
    {
        _collection.DeleteOne(Builders<T>.Filter.Eq("_id", id));
    }
}

使用该帮助类

public class MyEntity
{
    public string Id { get; set; }
    public string Name { get; set; }
}
 
// 获取所有记录
List<MyEntity> entities = MongoDBHelper<MyEntity>.GetAll();
 
// 通过ID获取单个记录
MyEntity entity = MongoDBHelper<MyEntity>.GetById("some_id");
 
// 插入新记录
MyEntity newEntity = new MyEntity { Name = "New Entity" };
MongoDBHelper<MyEntity>.Insert(newEntity);
 
// 更新记录
newEntity.Name = "Updated Name";
MongoDBHelper<MyEntity>.Update(newEntity);
 
// 删除记录
MongoDBHelper<MyEntity>.Delete("some_id");

 

posted @ 2024-11-06 17:56  天天向上518  阅读(14)  评论(0编辑  收藏  举报