Asp.Net Core MongoDB
废话不说直接上代码;
using MongoDB.Bson.Serialization.Attributes; namespace XL.Core.MongoDB
{
public interface IEntity<TKey>
{
/// <summary>
/// 主键
/// </summary>
[BsonId]
TKey Id { get; set; }
}
}
[BsonIgnoreExtraElements(Inherited = true)]
public abstract class Entity : IEntity<string>
{
/// <summary>
/// 主键
/// </summary>
[BsonRepresentation(BsonType.ObjectId)]
public virtual string Id { get; set; } }
public interface IRepository<T, in TKey> : IQueryable<T> where T : IEntity<TKey>
{
#region Fileds /// <summary>
/// MongoDB表
/// </summary>
IMongoCollection<T> DbSet { get; } /// <summary>
/// MongoDB库
/// </summary>
IMongoDatabase DbContext { get; } #endregion #region Find /// <summary>
/// 根据主键获取对象
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T GetById(TKey id); /// <summary>
/// 获取对象
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
IEnumerable<T> Get(Expression<Func<T, bool>> predicate); /// <summary>
/// 获取对象
/// </summary>
/// <param name="predicate"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Insert /// <summary>
/// 插入文档
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
T Insert(T entity); /// <summary>
/// 异步插入文档
/// </summary>
/// <param name="entity"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task InsertAsync(T entity, CancellationToken cancellationToken = default(CancellationToken)); /// <summary>
/// Adds the new entities in the repository.
/// </summary>
/// <param name="entities">The entities of type T.</param>
void Insert(IEnumerable<T> entities); /// <summary>
/// 插入文档
/// </summary>
/// <param name="entities"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task InsertAsync(IEnumerable<T> entities, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Update /// <summary>
/// 更新文档
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
UpdateResult Update(T entity); /// <summary>
/// 异步更新文档
/// </summary>
/// <param name="entity"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<UpdateResult> UpdateAsync(T entity, CancellationToken cancellationToken = default(CancellationToken)); #endregion #region Delete /// <summary>
/// 根据主键ID
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
T Delete(TKey id); /// <summary>
/// 异步根据ID删除文档
/// </summary>
/// <param name="id"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<T> DeleteAsync(TKey id, CancellationToken cancellationToken = default(CancellationToken)); /// <summary>
/// 异步删除
/// </summary>
/// <param name="predicate"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<DeleteResult> DeleteAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = default(CancellationToken)); /// <summary>
/// 删除
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
DeleteResult Delete(Expression<Func<T, bool>> predicate); #endregion #region Other /// <summary>
/// 计数
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
long Count(Expression<Func<T, bool>> predicate); /// <summary>
/// 计数
/// </summary>
/// <param name="predicate"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<long> CountAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = new CancellationToken()); /// <summary>
/// 是否存在
/// </summary>
/// <param name="predicate"></param>
/// <returns></returns>
bool Exists(Expression<Func<T, bool>> predicate); #endregion #region Query
/// <summary>
/// 分页
/// 注:只适合单属性排序
/// </summary>
/// <param name="predicate"></param>
/// <param name="sortBy"></param>
/// <param name="pageSize"></param>
/// <param name="pageIndex"></param>
/// <returns></returns>
IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
int pageSize, int pageIndex = );
/// <summary>
///
/// </summary>
/// <param name="predicate"></param>
/// <param name="sortBy"></param>
/// <param name="pageSize"></param>
/// <param name="pageIndex"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
int pageSize, int pageIndex = ,
CancellationToken cancellationToken = new CancellationToken()); #endregion
} public interface IRepository<T> : IRepository<T, string>
where T : IEntity<string>
{
}
public class MongoRepository<T> : IRepository<T> where T : IEntity<string>
{
#region Constructor protected MongoRepository(IMongoCollection<T> collection)
{
DbSet = collection;
DbContext = collection.Database;
} #endregion public IEnumerator<T> GetEnumerator()
{
return DbSet.AsQueryable().GetEnumerator();
} IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
} #region 字段 public Type ElementType => DbSet.AsQueryable().ElementType;
public Expression Expression => DbSet.AsQueryable().Expression;
public IQueryProvider Provider => DbSet.AsQueryable().Provider;
public IMongoCollection<T> DbSet { get; }
public IMongoDatabase DbContext { get; } #endregion #region Find public T GetById(string id)
{
return Get(a => a.Id.Equals(id)).FirstOrDefault();
} public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
{
return DbSet.FindSync(predicate).Current;
} public async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = new CancellationToken())
{
var task = await DbSet.FindAsync(predicate, null, cancellationToken);
return task.Current;
} #endregion #region Insert public T Insert(T entity)
{
DbSet.InsertOne(entity);
return entity;
} public Task InsertAsync(T entity, CancellationToken cancellationToken = new CancellationToken())
{
return DbSet.InsertOneAsync(entity, null, cancellationToken);
} public void Insert(IEnumerable<T> entities)
{
DbSet.InsertMany(entities);
} public Task InsertAsync(IEnumerable<T> entities, CancellationToken cancellationToken = new CancellationToken())
{
return DbSet.InsertManyAsync(entities, null, cancellationToken);
} #endregion #region Update public UpdateResult Update(T entity)
{
var doc = entity.ToBsonDocument();
return DbSet.UpdateOne(Builders<T>.Filter.Eq(e => e.Id, entity.Id),
new BsonDocumentUpdateDefinition<T>(doc));
} public Task<UpdateResult> UpdateAsync(T entity, CancellationToken cancellationToken = new CancellationToken())
{
var doc = entity.ToBsonDocument();
return DbSet.UpdateOneAsync(Builders<T>.Filter.Eq(e => e.Id, entity.Id),
new BsonDocumentUpdateDefinition<T>(doc), cancellationToken: cancellationToken);
} #endregion #region Delete public T Delete(string id)
{
return DbSet.FindOneAndDelete(a => a.Id.Equals(id));
} public Task<T> DeleteAsync(string id, CancellationToken cancellationToken = new CancellationToken())
{
return DbSet.FindOneAndDeleteAsync(a => a.Id.Equals(id), null, cancellationToken);
} public Task<DeleteResult> DeleteAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = new CancellationToken())
{
return DbSet.DeleteManyAsync(predicate, cancellationToken);
} public DeleteResult Delete(Expression<Func<T, bool>> predicate)
{
return DbSet.DeleteMany(predicate);
} #endregion #region Other public long Count(Expression<Func<T, bool>> predicate)
{
return DbSet.Count(predicate);
} public Task<long> CountAsync(Expression<Func<T, bool>> predicate,
CancellationToken cancellationToken = new CancellationToken())
{
return DbSet.CountAsync(predicate, null, cancellationToken);
} public bool Exists(Expression<Func<T, bool>> predicate)
{
return Get(predicate).Any();
} #endregion #region Page public IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
int pageSize, int pageIndex = )
{
var sort = Builders<T>.Sort.Descending(sortBy);
return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - ).Limit(pageSize).ToList();
} public Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,
int pageSize, int pageIndex = ,
CancellationToken cancellationToken = new CancellationToken())
{
return Task.Run(() =>
{
var sort = Builders<T>.Sort.Descending(sortBy);
return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - ).Limit(pageSize).ToList();
}, cancellationToken);
} #endregion #region Helper /// <summary>
/// 获取类型的所有属性信息
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TProperty"></typeparam>
/// <param name="select"></param>
/// <returns></returns>
private PropertyInfo[] GetPropertyInfos<TProperty>(Expression<Func<T, TProperty>> select)
{
var body = select.Body;
switch (body.NodeType)
{
case ExpressionType.Parameter:
var parameterExpression = body as ParameterExpression;
if (parameterExpression != null) return parameterExpression.Type.GetProperties();
break;
case ExpressionType.New:
var newExpression = body as NewExpression;
if (newExpression != null)
return newExpression.Members.Select(m => m as PropertyInfo).ToArray();
break;
}
return null;
} #endregion
}
使用如下:
public class MongoDBSetting
{
public string DataBase { get; set; } public string UserName { get; set; } public string Password { get; set; } public List<MongoServers> Services { get; set; }
} public class MongoServers
{
public string Host { get; set; } public int Port { get; set; } = ;
}
public class LogsContext
{
private readonly IMongoDatabase _db; public LogsContext(IOptions<MongoDBSetting> options) {
var permissionSystem =
MongoCredential.CreateCredential(options.Value.DataBase, options.Value.UserName,
options.Value.Password);
var services = new List<MongoServerAddress>();
foreach (var item in options.Value.Services)
{
services.Add(new MongoServerAddress(item.Host, item.Port));
}
var settings = new MongoClientSettings
{
Credentials = new[] {permissionSystem},
Servers = services
}; var _mongoClient = new MongoClient(settings);
_db = _mongoClient.GetDatabase(options.Value.DataBase);
} public IMongoCollection<ErrorLogs> ErrorLog => _db.GetCollection<ErrorLogs>("Error"); public IMongoCollection<ErrorLogs> WarningLog => _db.GetCollection<ErrorLogs>("Warning");
}
public static IServiceCollection UserMongoLog(this IServiceCollection services,
IConfigurationSection configurationSection)
{
services.Configure<MongoDBSetting>(configurationSection);
services.AddSingleton<LogsContext>();
return services;
}
public interface IErrorLogService : IRepository<ErrorLog>
{
}
public class ErrorLogService : MongoRepository<ErrorLog>, IErrorLogService
{
public ErrorLogService(LogsContext dbContext) : base(dbContext.ErrorLog)
{
}
}
最后:
services.UserMongoLog(Configuration.GetSection("Mongo.Log"));
"Mongo.Log": {
"DataBase": "PermissionSystem",
"UserName": "sa",
"Password": "shtx@123",
"Services": [
{
"Host": "192.168.1.6",
"Port": ""
}
]
}
刚学洗使用MongoDB,才疏学浅,请大神多多指教
Asp.Net Core MongoDB的更多相关文章
- ASP.NET Core+MongoDB(一)
项目类库:.Net Standar 2.0web:ASP.NET CORE 2.2 版本 先上图,看我们的解决方案结构: 分别对上面的工程进行说明:1.KYSharpCore:为公共的基础类,最底层 ...
- Asp.Net Core Use MongoDB
前几天在网上想找一下Asp.Net Core使用MongoDB相关的文章,也看了几篇,发现都是在写简单的例子,这样的例子是不能用在生产环境的,不能用的生产环境的.封装一个东西一定是建立在你对这个东西足 ...
- ASP.NET Core 实战:使用 NLog 将日志信息记录到 MongoDB
一.前言 在项目开发中,日志系统是系统的一个重要组成模块,通过在程序中记录运行日志.错误日志,可以让我们对于系统的运行情况做到很好的掌控.同时,收集日志不仅仅可以用于诊断排查错误,由于日志同样也是大量 ...
- Asp.Net Core Web Api图片上传(一)集成MongoDB存储实例教程
Asp.Net Core Web Api图片上传及MongoDB存储实例教程(一) 图片或者文件上传相信大家在开发中应该都会用到吧,有的时候还要对图片生成缩略图.那么如何在Asp.Net Core W ...
- Using MongoDB with Web API and ASP.NET Core
MongoDB is a NoSQL document-oriented database that allows you to define JSON based documents which a ...
- asp.net core集成MongoDB
0.目录 整体架构目录:ASP.NET Core分布式项目实战-目录 一.前言及MongoDB的介绍 最近在整合自己的框架,顺便把MongoDBD的最简单CRUD重构一下作为组件化集成到asp.net ...
- 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null
问题描述: POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null ...
- ASP.NET Core使用MongoDB数据库
环境:Asp.Net Core Mvc 2.2,MongoDB 4.09 参考文档:http://mongodb.github.io/mongo-csharp-driver/ http://mongo ...
- ASP.NET Core 之 Identity 入门(三)
前言 在上一篇文章中,我们学习了 CookieAuthentication 中间件,本篇的话主要看一下 Identity 本身. 最早2005年 ASP.NET 2.0 的时候开始, Web 应用程序 ...
随机推荐
- 当 C++ 遇上音乐
前几天在洛谷日报征文中看到了这样一篇文章:C++不止能做题.作为原来校管弦乐队的一名成员,而后因为信息完全放弃了管弦乐队,我看完是又激动又怀念.于是我自行去研究了一下:C++ 如何让蜂鸣器叫出乐曲. ...
- error CS1002: ; expected 错误解决
一般出现这种错误,大概原因是因为前端页面里的C#代码少个分号,或少个括号 导致编译器出错:仔细检查页面中的C#代码是否写的正确. 我之所以出现这个错误是因为前台页面中:@{ } 这里的代码少一个括号 ...
- JS 自由变量---JS 学习笔记(三) 补充
自由变量:在 A 中作用域要用到的变量 x,并没有在 A 中声明,要到别的作用域中找到他,这个变量 x 就是自由变量.代码示例如下: var x = 20; function A (b) { ret ...
- Kotlin 泛型
泛型,即 "参数化类型",将类型参数化,可以用在类,接口,方法上. 与 Java 一样,Kotlin 也提供泛型,为类型安全提供保证,消除类型强转的烦恼. 声明一个泛型类: cla ...
- Ubuntu16.04 使用sudo cat EOF 编辑文件,提示Permission denied错误的解决办法
一.执行命令报错 在Ubuntu16.04下,使用如下命令,修改hosts主机文件,居然提示权限错误: catty@node186:~$ sudo cat <<EOF > /etc/ ...
- js 回文判断
方法一: 1.toLowerCase() //统一小写. 2.split(" ").reverse().join(" "); //字符串翻转. func ...
- this的四种用法
函数运行时,自动生成的一个内部对象,只能在函数内部使用 随着函数使用场合的不同,this的值也发生着改变,但是有一个总原则:this指的是调用函数的那个对象(核心) 1.纯粹的函数调用 this指的是 ...
- round函数解决oracle报错"OCI-22053: 溢出错误"的问题
继上次公司网站报错除数为0的问题,这次又来报错溢出错误,还是同一条语句!搜索网上的解决方法,发现问题描述和解决方法如下: Oracle 数值数据类型最多可存储 38 个字节的精度.当将 Oracle ...
- EasyUI的textbox的disable ,readonly 用法
EasyUI的textbox,如果用了disable, 那么提交时,后台mvc controller是取不到值的, 如果用了Readonly, textbox的样式又没有变化, 让人一眼就感知到哪些是 ...
- 基于mykernel的时间片轮转调度
学号: 363 原创作品,转载请注明出处.本实验资源来源: https://github.com/mengning/linuxkernel/ 一. 实验环境配置 本次实验在实验楼完成: 在实验楼的终端 ...