搜索
首页后端开发C#.Net教程关于Asp.Net Core MongoDB的实例代码

关于Asp.Net Core MongoDB的实例代码

Jun 23, 2017 pm 04:17 PM
asp.netcoremongodb

废话不说直接上代码;

using MongoDB.Bson.Serialization.Attributes;namespace XL.Core.MongoDB
{public interface IEntity<TKey>{/// <summary>/// 主键/// </summary>        [BsonId]
        TKey Id { get; set; }
    }
}
View Code
    [BsonIgnoreExtraElements(Inherited = true)]public abstract class Entity : IEntity<string>{/// <summary>/// 主键/// </summary>        [BsonRepresentation(BsonType.ObjectId)]public virtual string Id { get; set; }
        
    }
View Code
    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>{
    }
View Code
  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}
View Code

使用如下:

    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;
    }
View Code

 

 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");
    }
View Code
 public static IServiceCollection UserMongoLog(this IServiceCollection services,
            IConfigurationSection configurationSection)
        {
            services.Configure<MongoDBSetting>(configurationSection);
            services.AddSingleton<LogsContext>();return services;
        }
View Code
public interface IErrorLogService : IRepository<ErrorLog>{
    }public class ErrorLogService : MongoRepository<ErrorLog>, IErrorLogService
    {public ErrorLogService(LogsContext dbContext) : base(dbContext.ErrorLog)
        {
        }
    }
View Code

最后:

services.UserMongoLog(Configuration.GetSection("Mongo.Log"));
View Code
"Mongo.Log": {"DataBase": "PermissionSystem","UserName": "sa","Password": "shtx@123","Services": [
      {"Host": "192.168.1.6","Port": "27017"  }
    ]
  }
View Code

刚学洗使用MongoDB,才疏学浅,请大神多多指教

以上是关于Asp.Net Core MongoDB的实例代码的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
C#和.NET运行时:它们如何一起工作C#和.NET运行时:它们如何一起工作Apr 19, 2025 am 12:04 AM

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

C#.NET开发:入门的初学者指南C#.NET开发:入门的初学者指南Apr 18, 2025 am 12:17 AM

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

c#和.net:了解两者之间的关系c#和.net:了解两者之间的关系Apr 17, 2025 am 12:07 AM

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

c#.net的持续相关性:查看当前用法c#.net的持续相关性:查看当前用法Apr 16, 2025 am 12:07 AM

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

从网络到桌面:C#.NET的多功能性从网络到桌面:C#.NET的多功能性Apr 15, 2025 am 12:07 AM

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

C#.NET与未来:适应新技术C#.NET与未来:适应新技术Apr 14, 2025 am 12:06 AM

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

c#.net适合您吗?评估其适用性c#.net适合您吗?评估其适用性Apr 13, 2025 am 12:03 AM

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

.NET中的C#代码:探索编程过程.NET中的C#代码:探索编程过程Apr 12, 2025 am 12:02 AM

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

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热工具

SecLists

SecLists

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

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 英文版

SublimeText3 英文版

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

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具