废话不说直接上代码;


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 = 1);/// <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 = 1, 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 Constructorprotected MongoRepository(IMongoCollection<T> collection) { DbSet = collection; DbContext = collection.Database; }#endregionpublic 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 Findpublic 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 Insertpublic 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 Updatepublic 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 Deletepublic 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 Otherpublic 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 Pagepublic IEnumerable<T> Paged(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,int pageSize, int pageIndex = 1) {var sort = Builders<T>.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList(); }public Task<List<T>> PagedAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> sortBy,int pageSize, int pageIndex = 1, CancellationToken cancellationToken = new CancellationToken()) {return Task.Run(() =>{var sort = Builders<T>.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).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; } = 27017; }


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": "27017" } ] }
刚学洗使用MongoDB,才疏学浅,请大神多多指教
以上是关于Asp.Net Core MongoDB的实例代码的详细内容。更多信息请关注PHP中文网其他相关文章!

C#和.NET运行时紧密合作,赋予开发者高效、强大且跨平台的开发能力。1)C#是一种类型安全且面向对象的编程语言,旨在与.NET框架无缝集成。2).NET运行时管理C#代码的执行,提供垃圾回收、类型安全等服务,确保高效和跨平台运行。

要开始C#.NET开发,你需要:1.了解C#的基础知识和.NET框架的核心概念;2.掌握变量、数据类型、控制结构、函数和类的基本概念;3.学习C#的高级特性,如LINQ和异步编程;4.熟悉常见错误的调试技巧和性能优化方法。通过这些步骤,你可以逐步深入C#.NET的世界,并编写高效的应用程序。

C#和.NET的关系是密不可分的,但它们不是一回事。C#是一门编程语言,而.NET是一个开发平台。C#用于编写代码,编译成.NET的中间语言(IL),由.NET运行时(CLR)执行。

C#.NET依然重要,因为它提供了强大的工具和库,支持多种应用开发。1)C#结合.NET框架,使开发高效便捷。2)C#的类型安全和垃圾回收机制增强了其优势。3).NET提供跨平台运行环境和丰富的API,提升了开发灵活性。

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C#和.NET通过不断的更新和优化,适应了新兴技术的需求。1)C#9.0和.NET5引入了记录类型和性能优化。2).NETCore增强了云原生和容器化支持。3)ASP.NETCore与现代Web技术集成。4)ML.NET支持机器学习和人工智能。5)异步编程和最佳实践提升了性能。

c#.netissutableforenterprise-levelapplications withemofrosoftecosystemdueToItsStrongTyping,richlibraries,androbustperraries,androbustperformance.however,itmaynotbeidealfoross-platement forment forment forment forvepentment offependment dovelopment toveloperment toveloperment whenrawspeedsportor whenrawspeedseedpolitical politionalitable,

C#在.NET中的编程过程包括以下步骤:1)编写C#代码,2)编译为中间语言(IL),3)由.NET运行时(CLR)执行。C#在.NET中的优势在于其现代化语法、强大的类型系统和与.NET框架的紧密集成,适用于从桌面应用到Web服务的各种开发场景。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

禅工作室 13.0.1
功能强大的PHP集成开发环境

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具