C# 引用mongo的dll文件 构建访问基类
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
namespace MyMongo.Mongo
{
public class MongoHelper<T> where T : class
{
public MongoCollection<T> Collection { get; private set; }
public MongoHelper()
{
var con = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
var server = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString).GetServer();
var db = server.GetDatabase(con.DatabaseName);
Collection = db.GetCollection<T>(typeof(T).Name.ToLower());
}
}
}
具体使用方法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver.Linq;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.Builders;
namespace MyMongo.MongoCore.DataService
{
public class UserService
{
private readonly MongoHelper<User> _user;
public UserService()
{
_user = new MongoHelper<User>();
}
// 增、删、改、查 方法
}
}
配置字符串
<add name="MongoDB"connectionString="server=localhost;database=local" />