.net core MongoDB 初试
是这样的,我们有一个场景,另一个服务器是写到MongoDB里面,我们的MVC页面要展示,需要分页展示
自己写了一个DAL
public class MongoConnect
{
public string ConnectString { get; set; }
} public class MongoBaseDAL<TEntity>
{
public MongoBaseDAL(IOptions<MongoConnect> options)
{
ConnectString = options.Value.ConnectString;
} private string ConnectString { get; set; } = "192.168.50.110:27017"; protected MongoClient Create()
{
var client = new MongoClient($"mongodb://{ConnectString}");
return client;
} protected IMongoDatabase GetDatabase(string database)
{
var client = Create();
var db = client.GetDatabase(database); return db;
} protected IMongoCollection<TEntity> CreateQuery(string database,string tableName)
{
var db = GetDatabase(database);
return db.GetCollection<TEntity>(tableName);
} protected PageDataView<TEntity> Page(string database, string tableName, Dictionary<string, BsonValue> dictionary, int pageSize, int currentPage)
{
var where = Builders<TEntity>.Filter.Empty;
if (dictionary.Count > )
{
var filterBuilder = Builders<TEntity>.Filter; List<FilterDefinition<TEntity>> listFilter = new List<FilterDefinition<TEntity>>(); foreach (var pair in dictionary)
{
listFilter.Add(filterBuilder.Eq(pair.Key, pair.Value));
} where = filterBuilder.And(listFilter);
} PageDataView<TEntity> result = new PageDataView<TEntity>(); var query = CreateQuery(database, tableName);
result.TotalRecords = (int)query.CountDocuments(where);
result.TotalPages = result.TotalRecords / pageSize;
if (result.TotalRecords % pageSize > )
result.TotalPages += ; var list = query.Find(where).Skip((currentPage - ) * pageSize).Limit(pageSize).ToList();
result.Items = list; return result;
}
}
比如有个类CreatedTableLog
那个Helper就是
public class CreatedTableLogHelper: MongoBaseDAL<CreatedTableLog>
{
public static string Database = "Base";
public static string Table = "CreatedTableLog"; public CreatedTableLogHelper(IOptions<MongoConnect> options) : base(options)
{
} public PageDataView<CreatedTableLog> GetListByPage(Dictionary<string, BsonValue> dictionary, int pageSize, int currentPage)
{
return Page(Database, Table, dictionary, pageSize, currentPage);
}
}
在StartUp里面增加代码
#region MongoDB
services.Configure<MongoConnect>(Configuration.GetSection("MongoConnect"));
services.AddScoped(typeof(MongoBaseDAL<>));
services.AddScoped<CreatedTableLogHelper>();
#endregion
打开配置文件
appsettings.Development.json这个是DEBUG版本的配置文件
写入配置
"MongoConnect": {
"ConnectString": "192.168.50.110:27017"
}
192.168.50.110是我测试环境是MongoDB服务器地址,端口默认
appsettings.Development.json这个是Release版本的配置文件可能这个地址就是localhost了,要对应更改
比如CreatedTableLog表有三个字段
UserId和NickName需要查询
Dictionary<string, BsonValue> dictionary = new Dictionary<string, BsonValue>();
var index = model.Start == ? : (model.Start / model.Length) + ;
if (model.UserId != )
{
dictionary.Add("UserId", BsonInt64.Create(model.UserId));
}
if (!string.IsNullOrWhiteSpace(model.NickName))
{
dictionary.Add("NickName", BsonString.Create(model.NickName));
}
var result = CreatedTableLogHelper.GetListByPage(dictionary, model.Length, index);
这样你以为就ok了?no no no
会报错的,为什么同一个实体model,写入正常,读会报错_id错误呢?
因为实体model如果没有Id类型是ObjectId,会自动构建,但是你反序列化就会错误了
增加一个继承类
public class MongoDbBase
{
private ObjectId _id;
public ObjectId Id
{
get { return _id; }
set { _id = value; }
}
}
你需要反序列化的实体对象继承
比如CreatedTableLog改为
public class CreatedTableLog: MongoDbBase
再读一下,对了吧?大功告成
.net core MongoDB 初试的更多相关文章
- Asp.Net Core MongoDB
废话不说直接上代码: using MongoDB.Bson.Serialization.Attributes; namespace XL.Core.MongoDB { public interface ...
- .Net Core MongoDB 简单操作。
一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...
- ASP.NET Core+MongoDB(一)
项目类库:.Net Standar 2.0web:ASP.NET CORE 2.2 版本 先上图,看我们的解决方案结构: 分别对上面的工程进行说明:1.KYSharpCore:为公共的基础类,最底层 ...
- .NET Core+MongoDB集群搭建与实战
目录 安装 MongoDB apt 直接安装(方法1) apt 仓库安装(方法2) 方法1.2启动 MongoDB 通过二进制包安装(方法3) 安装依赖 deb 安装 MongoDB tgz 安装 M ...
- MongoDB—— 写操作 Core MongoDB Operations (CRUD)
MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略. 主要有三种写操作: Create Update ...
- MongoDB—— 读操作 Core MongoDB Operations (CRUD)
本文主要介绍内容:从MongoDB中请求数据的不同的方法 Note:All of the examples in this document use the mongo shell interface ...
- MongoDB初试备份及恢复
MongoDB作为文档数据库,有 1.登录MongoDB官网,地址:https://www.mongodb.com/download-center#community , 根据自己操作系统下载相应版 ...
- .net Core MongoDB用法演示
C#驱动MongoDB的本质是将C#的操作代码转换为mongo shell,驱动的API也比较简单明了,方法名和js shell的方法名基本都保持一致,熟悉mongo shell后学习MongoDB的 ...
- Core Data初试
CoreDataStack.swift import CoreData class CoreDataStack: NSObject { let context: NSManagedObjectCont ...
随机推荐
- day56 js收尾,jQuery前戏
目录 一.原生js事件绑定 1 开关灯案例 2 input框获取焦点,失去焦点案例 3 实现展示当前时间,定时功能 4 省市联动 二.jQuery入门 1 jQuery的两种导入方式 1.1 直接下载 ...
- SQL字符串拼接FOR XML PATH
在工作中难免会遇到数据库中数据要进行拼接的问题,字符串拼接可以是用SQL的拼接也可以使用C#的拼接,本次说的是使用SQL进行拼接. 首先插入测试语句: --测试语句,准备创建表的语句:如下 CREAT ...
- pip install scrapy报错:error: Unable to find vcvarsall.bat解决方法
今天在使用pip install scrapy 命令安装Scrapy爬虫框架时,出现了很让人头疼的错误,错误截图如下: 在网上查找解决方法时,大致知道了问题的原因.是因为缺少C语言的编译环境,其中一种 ...
- python eval函数,将列表样式的字符串转化为列表
python eval函数,将列表样式的字符串转化为列表 >>> str_1 = '[1,2,3,4,5,6]'>>> type(str_1)<type 's ...
- python 爬虫:HTTP ERROR 406
解决方法: 设置了Accept头后解决了,但是还是不知道原因 headers:{ Accept:"text/html, application/xhtml+xml, */*" }原 ...
- MapReduce计算框架的核心编程思想
@ 目录 概念 MapReduce中常用的组件 概念 Job(作业) : 一个MapReduce程序称为一个Job. MRAppMaster(MR任务的主节点): 一个Job在运行时,会先启动一个进程 ...
- Tomcat的结构
Tomcat其实就是一个容器,最顶层的容器叫Server,代表整个服务器,Server中包含至少一个Service,用于具体提供服务.Service主要包含两部分:Connector和Containe ...
- 《重学 Java 设计模式》PDF 出炉了 - 小傅哥,肝了50天写出18万字271页的实战编程资料
作者:小傅哥 博客:https://bugstack.cn 沉淀.分享.成长,让自己和他人都能有所收获! @ 目录 一.前言 二.简介 1. 谁发明了设计模式? 2. 我怎么学不会设计模式? 3. 适 ...
- GitHub 热点速览 Vol.28:有品位程序员的自我修养
作者:HelloGitHub-小鱼干 摘要:一个程序员除了技术好,还得品位高,有什么比一个高颜值的 GUI 更能体现你品味的呢?rocketredis 就是一个高颜值.简约的 Redis 管理界面,比 ...
- Linux下一只五颜六色的「猫」
大家好,我是良许. 有使用过 Linux 系统的小伙伴,肯定会使用过 cat 这个命令.当然,在 Linux 下,此猫非彼猫,这里的 cat 并不代表猫,而是单词 concatenate 的缩写. c ...