0

0

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

零下一度

零下一度

发布时间:2017-06-23 16:17:43

|

2395人浏览过

|

来源于php中文网

原创

废话不说直接上代码;

using MongoDB.Bson.Serialization.Attributes;namespace XL.Core.MongoDB
{public interface IEntity{/// /// 主键///         [BsonId]
        TKey Id { get; set; }
    }
}
View Code
    [BsonIgnoreExtraElements(Inherited = true)]public abstract class Entity : IEntity{/// /// 主键///         [BsonRepresentation(BsonType.ObjectId)]public virtual string Id { get; set; }
        
    }
View Code
    public interface IRepository : IQueryable where T : IEntity{#region Fileds/// /// MongoDB表/// IMongoCollection DbSet { get; }/// /// MongoDB库/// IMongoDatabase DbContext { get; }#endregion#region Find/// /// 根据主键获取对象/// /// ///         T GetById(TKey id);/// /// 获取对象/// /// /// IEnumerable Get(Expression> predicate);/// /// 获取对象/// /// /// /// Task> GetAsync(Expression> predicate,
            CancellationToken cancellationToken = default(CancellationToken));#endregion#region Insert/// /// 插入文档/// /// ///         T Insert(T entity);/// /// 异步插入文档/// /// /// /// Task InsertAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));/// ///     Adds the new entities in the repository./// /// The entities of type T.void Insert(IEnumerable entities);/// /// 插入文档/// /// /// /// Task InsertAsync(IEnumerable entities, CancellationToken cancellationToken = default(CancellationToken));#endregion#region Update/// /// 更新文档/// /// ///         UpdateResult Update(T entity);/// /// 异步更新文档/// /// /// /// Task UpdateAsync(T entity, CancellationToken cancellationToken = default(CancellationToken));#endregion#region Delete/// /// 根据主键ID/// /// ///         T Delete(TKey id);/// /// 异步根据ID删除文档/// /// /// /// Task DeleteAsync(TKey id, CancellationToken cancellationToken = default(CancellationToken));/// /// 异步删除/// /// /// /// Task DeleteAsync(Expression> predicate,
            CancellationToken cancellationToken = default(CancellationToken));/// /// 删除/// /// /// DeleteResult Delete(Expression> predicate);#endregion#region Other/// /// 计数/// /// /// long Count(Expression> predicate);/// /// 计数/// /// /// /// Task CountAsync(Expression> predicate,
            CancellationToken cancellationToken = new CancellationToken());/// /// 是否存在/// /// /// bool Exists(Expression> predicate);#endregion#region Query/// /// 分页/// 注:只适合单属性排序/// /// /// /// /// /// IEnumerable Paged(Expression> predicate, Expression> sortBy,int pageSize, int pageIndex = 1);/// /// /// /// /// /// /// /// /// Task> PagedAsync(Expression> predicate, Expression> sortBy,int pageSize, int pageIndex = 1,
            CancellationToken cancellationToken = new CancellationToken());#endregion}  public interface IRepository : IRepositorywhere T : IEntity{
    }
View Code
  public class MongoRepository : IRepository where T : IEntity{#region Constructorprotected MongoRepository(IMongoCollection collection)
        {
            DbSet = collection;
            DbContext = collection.Database;
        }#endregionpublic IEnumerator 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 DbSet { get; }public IMongoDatabase DbContext { get; }#endregion#region Findpublic T GetById(string id)
        {return Get(a => a.Id.Equals(id)).FirstOrDefault();
        }public IEnumerable Get(Expression> predicate)
        {return DbSet.FindSync(predicate).Current;
        }public async Task> GetAsync(Expression> 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 entities)
        {
            DbSet.InsertMany(entities);
        }public Task InsertAsync(IEnumerable 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.Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition(doc));
        }public Task UpdateAsync(T entity, CancellationToken cancellationToken = new CancellationToken())
        {var doc = entity.ToBsonDocument();return DbSet.UpdateOneAsync(Builders.Filter.Eq(e => e.Id, entity.Id),new BsonDocumentUpdateDefinition(doc), cancellationToken: cancellationToken);
        }#endregion#region Deletepublic T Delete(string id)
        {return DbSet.FindOneAndDelete(a => a.Id.Equals(id));
        }public Task DeleteAsync(string id, CancellationToken cancellationToken = new CancellationToken())
        {return DbSet.FindOneAndDeleteAsync(a => a.Id.Equals(id), null, cancellationToken);
        }public Task DeleteAsync(Expression> predicate,
            CancellationToken cancellationToken = new CancellationToken())
        {return DbSet.DeleteManyAsync(predicate, cancellationToken);
        }public DeleteResult Delete(Expression> predicate)
        {return DbSet.DeleteMany(predicate);
        }#endregion#region Otherpublic long Count(Expression> predicate)
        {return DbSet.Count(predicate);
        }public Task CountAsync(Expression> predicate,
            CancellationToken cancellationToken = new CancellationToken())
        {return DbSet.CountAsync(predicate, null, cancellationToken);
        }public bool Exists(Expression> predicate)
        {return Get(predicate).Any();
        }#endregion#region Pagepublic IEnumerable Paged(Expression> predicate, Expression> sortBy,int pageSize, int pageIndex = 1)
        {var sort = Builders.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList();
        }public Task> PagedAsync(Expression> predicate, Expression> sortBy,int pageSize, int pageIndex = 1,
            CancellationToken cancellationToken = new CancellationToken())
        {return Task.Run(() =>{var sort = Builders.Sort.Descending(sortBy);return DbSet.Find(predicate).Sort(sort).Skip(pageSize * pageIndex - 1).Limit(pageSize).ToList();
            }, cancellationToken);
        }#endregion#region Helper/// /// 获取类型的所有属性信息/// /// /// /// /// private PropertyInfo[] GetPropertyInfos(Expression> 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 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 options)

        {var permissionSystem =MongoCredential.CreateCredential(options.Value.DataBase, options.Value.UserName,
                    options.Value.Password);var services = new List();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 ErrorLog => _db.GetCollection("Error");public IMongoCollection WarningLog => _db.GetCollection("Warning");
    }
View Code
 public static IServiceCollection UserMongoLog(this IServiceCollection services,
            IConfigurationSection configurationSection)
        {
            services.Configure(configurationSection);
            services.AddSingleton();return services;
        }
View Code
public interface IErrorLogService : IRepository{
    }public class ErrorLogService : MongoRepository, IErrorLogService
    {public ErrorLogService(LogsContext dbContext) : base(dbContext.ErrorLog)
        {
        }
    }
View Code

最后:

CodiumAI
CodiumAI

AI代码测试工具,在IDE中获得重要的测试建议

下载
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,才疏学浅,请大神多多指教

相关专题

更多
c++ 根号
c++ 根号

本专题整合了c++根号相关教程,阅读专题下面的文章了解更多详细内容。

57

2026.01.23

c++空格相关教程合集
c++空格相关教程合集

本专题整合了c++空格相关教程,阅读专题下面的文章了解更多详细内容。

57

2026.01.23

yy漫画官方登录入口地址合集
yy漫画官方登录入口地址合集

本专题整合了yy漫画入口相关合集,阅读专题下面的文章了解更多详细内容。

237

2026.01.23

漫蛙最新入口地址汇总2026
漫蛙最新入口地址汇总2026

本专题整合了漫蛙最新入口地址大全,阅读专题下面的文章了解更多详细内容。

393

2026.01.23

C++ 高级模板编程与元编程
C++ 高级模板编程与元编程

本专题深入讲解 C++ 中的高级模板编程与元编程技术,涵盖模板特化、SFINAE、模板递归、类型萃取、编译时常量与计算、C++17 的折叠表达式与变长模板参数等。通过多个实际示例,帮助开发者掌握 如何利用 C++ 模板机制编写高效、可扩展的通用代码,并提升代码的灵活性与性能。

17

2026.01.23

php远程文件教程合集
php远程文件教程合集

本专题整合了php远程文件相关教程,阅读专题下面的文章了解更多详细内容。

103

2026.01.22

PHP后端开发相关内容汇总
PHP后端开发相关内容汇总

本专题整合了PHP后端开发相关内容,阅读专题下面的文章了解更多详细内容。

73

2026.01.22

php会话教程合集
php会话教程合集

本专题整合了php会话教程相关合集,阅读专题下面的文章了解更多详细内容。

81

2026.01.22

宝塔PHP8.4相关教程汇总
宝塔PHP8.4相关教程汇总

本专题整合了宝塔PHP8.4相关教程,阅读专题下面的文章了解更多详细内容。

70

2026.01.22

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
ASP.NET参考手册
ASP.NET参考手册

共0课时 | 0人学习

传播智客ASP.NET中级系列视频教程
传播智客ASP.NET中级系列视频教程

共33课时 | 6.4万人学习

传播智客ASP.NET高级系列视频教程
传播智客ASP.NET高级系列视频教程

共34课时 | 6.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号