是这样的,我们有一个场景,另一个服务器是写到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. 【转】Web端测试点整理

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/qq_24373725/article/d ...

  2. day17 生成器, 面向过程, 三元表达式, 生成式

    1. 生成器 生成器:就是一种自定义的迭代器,是用来返回多次值自定义迭代器的好处:节省内存 return只能返回一次值,函数就立即结束了yield 1.可以挂起函数,保存函数的运行状态 2.可以用来返 ...

  3. 为什么通常在发送数据埋点请求的时候使用的是 1x1 像素的透明 gif 图片?

    避免跨域(img 天然支持跨域) 利用空白gif或1x1 px的img是互联网广告或网站监测方面常用的手段,简单.安全.相比PNG/JPG体积小,1px 透明图,对网页内容的影响几乎没有影响,这种请求 ...

  4. requests接口自动化9-共享session和传递cookie

    前言: session:用requests.session()创建会话,可以将会话信息传递给其他接口 cookie:用RequestsCookieJar或者cookie字典传递cookie信息 fil ...

  5. Mysql基础(二):MySQL之存储引擎

    目录 MySQL之存储引擎 1.MySQL存储引擎介绍 2.MySQL结构 3.MySQL存储引擎分类 4.存储引擎的使用 5.总结 MySQL之存储引擎 1.MySQL存储引擎介绍 MySQL中的数 ...

  6. 数据可视化之powerBI基础(四)深入了解PowerBI的工具提示功能

    https://zhuanlan.zhihu.com/p/36804592 在PowerBI上个月的更新中,增加了工具提示功能,这项功能允许您将自己的可视化作品放置到工具提示中,通过鼠标悬停的方式来展 ...

  7. Azure Web App (二)使用部署槽切换部署环境

    一,引言 前天我们将到使用Azure的 Pass 服务 “Web App” 去部署我们的.NET Core Web项目,也同时有介绍到如何在VS中配置登陆中国区的Azure账号,今天接着讲,我们部署完 ...

  8. Ethical Hacking - Web Penetration Testing(4)

    CODE EXECUTION VULNS Allows an attacker to execute OS commands. Windows or Linux commands. Can be us ...

  9. T1 找试场 题解

    拖延症又犯了QwQ. 今天上午考试了,按照惯例,我仍然要把我会的所有题的题解写一遍. 1.找试场(way.cpp/in/out) 问题描述 小王同学在坐标系的(0,0)处,但是他找不到考试的试场,于是 ...

  10. 题解 洛谷 P2287 [USACO07NOV]Sunscreen G

    原题 传送门 有C个奶牛去晒太阳 (1 <=C <= 2500),每个奶牛各自能够忍受的阳光强度有一个最小值和一个最大值(minSPFi and maxSPFi),太大就晒伤了,太小奶牛没 ...