CJCMS系列--持久层对MangoDB的支持
持久层添加对MangoDB数据库的支持
using System; using System.Collections.Generic; using System.Linq; using System.Text; using CJCMS.Data; using MongoDB.Bson; using MongoDB.Driver; using MongoDB.Driver.Builders; using MongoDB.Driver.GridFS; using MongoDB.Driver.Linq; using System.Linq.Expressions; namespace CJCMS.Data { public class MangoDBRepository<T> : IRepository<T> where T : IEntity { MongoCollection<T> _session = null; public MangoDBRepository() { //读配置 string connectionString = "mongodb://localhost"; MongoClient client = new MongoClient(connectionString); var server = client.GetServer(); //读配置 var database = server.GetDatabase("test"); //获取T的名称 _session = database.GetCollection<T>("tableName"); } public void Add(T entity) { _session.Insert(entity); } public IQueryable<T> Table { get { return _session.AsQueryable<T>(); } } public void Update(T entity) { _session.Save(entity); } public void Save(T entity) { _session.Save(entity); } public void Delete(T entity) { var query = Query<T>.EQ(e => e.Id, entity.Id); _session.Remove(query); } public void Delete(string id) { var query = Query<T>.EQ(e => e.Id, id); _session.Remove(query); } public T GetByKey(string id) { var query = Query<T>.EQ(e => e.Id, id); T t = _session.FindOneAs<T>(query); return t; } public int Count(Expression<Func<T, bool>> predicate) { return Table.Count(predicate); } private IQueryable<T> FetchQuery(Expression<Func<T, bool>> predicate) { return Table.Where(predicate); } private IQueryable<T> FetchQuery(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order, out string OrderName) { var orderable = new Orderable<T>(FetchQuery(predicate)); order(orderable); OrderName = orderable.OrderName; return orderable.Queryable; } public IList<T> Fetch(Expression<Func<T, bool>> predicate) { object t = null; if (t == null) { t = FetchQuery(predicate).ToList(); return (IList<T>)t; } else { return (IList<T>)t; } } public IList<T> Fetch(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order) { object t = null; string key = string.Empty; IQueryable<T> q = FetchQuery(predicate, order, out key); if (t == null) { t = q.ToList(); return (IList<T>)t; } else { q = null; return (IList<T>)t; } } public IList<T> Fetch(Expression<Func<T, bool>> predicate, Action<Orderable<T>> order, int index, int count) { object t = null; string key = string.Empty; IQueryable<T> q = FetchQuery(predicate, order, out key); if (t == null) { t = q.Skip(index * count).Take(count).ToList(); return (IList<T>)t; } else { q = null; return (IList<T>)t; } } public void Persist() { } } }