.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 ...
随机推荐
- JavaScript图片预览
预览选中的图片文件 jQuery $("#selectImage").change(function(){ $("#image").attr("src ...
- 二分查找&二叉排序树
首先我们先来复习一下二分查找的算法 对于正向序列的二分查找 递归实现: bool binary_search(vector<int> &sort_arry,int begin,in ...
- Kafka入门(1):概述
摘要 在本文中,我将从为什么需要消息队列开始讲起,举两个小例子,跟你聊聊目前消息队列的一些使用场景. 比如消息队列在复杂系统中的解耦,又比如消息队列在高并发下的场景如果让流量变得更平缓. 随后我会跟你 ...
- 记录一次dns引发的线程池故障
# 问题描述 公司做的是一个支付系统,会对接很多第三方公司. 突然有一天,有一家第三方(简称金花平台)反应收不到我们的通知消息. # 排查过程 我们登陆自己的服务器,检查程序日志,是有给金花平台发送通 ...
- MYSQL 之 JDBC(十): JDBC的元数据
可以从Connection对象中获得有关数据库管理系统的各种信息 获取这些信息的方法都是在DatabaseMetaData类中. DatabaseMetaData:描述数据库的元数据对象 Result ...
- 最大熵原理(The Maximum Entropy Principle)
https://wanghuaishi.wordpress.com/2017/02/21/%E5%9B%BE%E8%A7%A3%E6%9C%80%E5%A4%A7%E7%86%B5%E5%8E%9F% ...
- nginx 信号管理
本内容只针对nginx 关闭操作罗列方法技巧,不废话直接写,Nginx的信号控制如下: 1. TERM, INT 强制关闭进程 查看nginx进程ps -aux|grep nginx root 8 ...
- Java常用API(String类)
Java常用API(String类) 概述: java.lang.String 类代表字符串.Java程序中所有的字符串文字(例如 "abc" )都可以被看作是实现此类的实例 1. ...
- C++算法 广搜
有一个同学推荐我写一下广搜,广搜在最短路(骗分)上确实也有突出贡献,普及组应该也会考到,我今天就给要考普及组的同学讲讲课,今天讲广搜. 广搜,把可以走到的地点存进队列,然后一个个走,所以他第一次走到一 ...
- less : 写一个display:flex的mixin
和scss一样,less也是一个好用的css预处理语言,语法也很相近. 而我们在使用display:flex的时候,很容易苦恼于里面的设置的单词很难记(尤其是对我这种英语很差的人来说). 所以我们可以 ...