是这样的,我们有一个场景,另一个服务器是写到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 初试的更多相关文章

  1. Asp.Net Core MongoDB

    废话不说直接上代码: using MongoDB.Bson.Serialization.Attributes; namespace XL.Core.MongoDB { public interface ...

  2. .Net Core MongoDB 简单操作。

    一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...

  3. ASP.NET Core+MongoDB(一)

    项目类库:.Net Standar 2.0web:ASP.NET CORE 2.2 版本 先上图,看我们的解决方案结构: 分别对上面的工程进行说明:1.KYSharpCore:为公共的基础类,最底层 ...

  4. .NET Core+MongoDB集群搭建与实战

    目录 安装 MongoDB apt 直接安装(方法1) apt 仓库安装(方法2) 方法1.2启动 MongoDB 通过二进制包安装(方法3) 安装依赖 deb 安装 MongoDB tgz 安装 M ...

  5. MongoDB—— 写操作 Core MongoDB Operations (CRUD)

    MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略. 主要有三种写操作:        Create        Update        ...

  6. MongoDB—— 读操作 Core MongoDB Operations (CRUD)

    本文主要介绍内容:从MongoDB中请求数据的不同的方法 Note:All of the examples in this document use the mongo shell interface ...

  7. MongoDB初试备份及恢复

    MongoDB作为文档数据库,有 1.登录MongoDB官网,地址:https://www.mongodb.com/download-center#community  , 根据自己操作系统下载相应版 ...

  8. .net Core MongoDB用法演示

    C#驱动MongoDB的本质是将C#的操作代码转换为mongo shell,驱动的API也比较简单明了,方法名和js shell的方法名基本都保持一致,熟悉mongo shell后学习MongoDB的 ...

  9. Core Data初试

    CoreDataStack.swift import CoreData class CoreDataStack: NSObject { let context: NSManagedObjectCont ...

随机推荐

  1. VS2019阅读源码 翻译注释插件

    VS翻译插件: Comment Translator China https://marketplace.visualstudio.com/items?itemName=netcorevip.Comm ...

  2. 一篇文章掌握 Python 内置 zip() 的全部内容

    一篇文章掌握 Python 内置 zip() 的全部内容 zip() 是 Python 中最好用的内置类型之一,它可以接收多个可迭代对象参数,再返回一个迭代器,可以把不同可迭代对象的元素组合起来. 我 ...

  3. if-else和三目运算符 ? : 的对比

    今天的地铁思考让我想起一个之前学C语言的时候一直没有验证的事情:既生瑜何生亮? 平时写代码的时候,似乎并没有太多的关注我应该选用什么条件判断语句,感觉判断条件或者两条支路语句复杂就本能地if-else ...

  4. web 部署专题(九):Nginx 前后端分离中csrf_token 认证的实现

    1. 思路 参考:https://stackoverflow.com/questions/20826201/simple-csrf-protection-using-nginx-alone?r=Sea ...

  5. 机器学习实战基础(二十四):sklearn中的降维算法PCA和SVD(五) PCA与SVD 之 重要接口inverse_transform

    重要接口inverse_transform  在上周的特征工程课中,我们学到了神奇的接口inverse_transform,可以将我们归一化,标准化,甚至做过哑变量的特征矩阵还原回原始数据中的特征矩阵 ...

  6. Python之爬虫(七)正则的基本使用

    什么是正则表达式 正则表达式是对字符串操作的一种逻辑公式,就是 事先定义好的一些特定字符.及这些特定字符的组合,组成一个“规则字符”,这个“规则字符” 来表达对字符的一种过滤逻辑. 正则并不是pyth ...

  7. python爬虫学习01--电子书爬取

    python爬虫学习01--电子书爬取 1.获取网页信息 import requests #导入requests库 ''' 获取网页信息 ''' if __name__ == '__main__': ...

  8. CSS背景处理

    CSS背景处理 背景样式 背景颜色 如果想让一个区域具有纯色的背景,可以使用background-color进行设置,背景颜色可以是rgb,rgba,#16网页色. <!DOCTYPE html ...

  9. 用Python演奏音乐

    目录 背景 准备 安装mingus 下载并配置fluidsynth 下载soundfont文件 分析 乐谱格式 乐谱解析 弹奏音乐 添加伴奏 保存音乐 完整程序 背景 笔者什么乐器也不会,乐理知识也只 ...

  10. Python数据分析实战:使用pyecharts进行数据可视化

    前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:刘早起 开始使用 基本套路就是先创建一个你需要的空图层,然后使用.s ...