.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 > 0){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 > 0)result.TotalPages += 1;var list = query.Find(where).Skip((currentPage - 1) * 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 MongoDBservices.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 == 0 ? 1 : (model.Start / model.Length) + 1;if (model.UserId != 0){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

再讀一下,對了吧?大功告成

轉載于:https://www.cnblogs.com/NCoreCoder/p/9870030.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/279082.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/279082.shtml
英文地址,請注明出處:http://en.pswp.cn/news/279082.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Linux文件和目錄權限:chmod、更改所有者和所屬組:chown,umask命令,隱藏權限:lsattr/chattr...

文件和目錄權限chmod&#xff1a; 我們使用ls -l可以看到文件的詳細信息&#xff0c;也知道第一列的第一個符號(字母)表示文件的類型&#xff0c;在表示文件的類型符號的后面的九個符號則表示的是文件的權限&#xff0c;這些權限和文件的所有者和所屬組都有關系&#xff1a; 文…

【技術累積】【點】【java】【27】@JSONField

JSONField 該注解隸屬于阿里fastjson&#xff0c;方便fastjson處理對象時的一些操作 源碼 Retention(RetentionPolicy.RUNTIME) Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) public interface JSONField {/*** config encode/decode ordinal* s…

百度php editor圖片上傳到其他盤,百度編輯器Editor圖片獨立上傳

將百度編輯器中的圖片獨立出來上傳&#xff1a;html:代碼var myEditorImage,d,myEditorImage new UE.ui.Editor();myEditorImage.render(uploadid);myEditorImage.ready(function(){myEditorImage.setDisabled();myEditorImage.hide();//隱藏UE框體myEditorImage.addListener(…

感謝支持,超預期重印并加碼

今天&#xff0c;要向廣大讀者朋友帶來一個&#xff0c;連我自己和出版社都感到十分意外的好消息&#xff0c;幾天前接到出版社的通知&#xff0c;說今年元月出版的《Cisco/H3C交換機配置與管理完全手冊》&#xff08;第二版&#xff09;馬上就要下單重印了&#xff0c;而且一下…

如何從手機遠程控制uTorrent

You’re a geek on the go and it’s important to keep tabs on your torrents when you’re away from home. Today we take a peak at how you can monitor, manage, and even start your torrent downloads when you’re away from your computer. 您是旅途中的怪胎&#x…

洛谷P2463 Sandy的卡片【后綴數組】【二分】

題目描述 Sandy和Sue的熱衷于收集干脆面中的卡片。 然而&#xff0c;Sue收集卡片是因為卡片上漂亮的人物形象&#xff0c;而Sandy則是為了積攢卡片兌換超炫的人物模型。 每一張卡片都由一些數字進行標記&#xff0c;第i張卡片的序列長度為Mi&#xff0c;要想兌換人物模型&#…

php獲取一個文件名的函數,PHP 文件系統函數之獲取文件名及文件名后綴-php文件...

獲取文件名(包含擴展):1.用PHP 文件函數 basename獲取例&#xff1a;$filename "/home/httpd/html/index.php";$file basename($filename);2.先獲取位置再獲取文件名例:$filename "/home/httpd/html/index.php";$pos strrpos($filename, /);if ($pos …

tasker使用手冊_如何開始使用Tasker調整Android手機

tasker使用手冊Tasker is a powerful app for Android that lets you customize how your phone works and automate tasks. Unfortunately, it’s got a bit of a learning curve. We’re here to show you how to get started and turn your phone into a flashlight in the …

iPhone 軟件:xlate free 編碼的好幫手!

功能菜單&#xff1a; 1 文本 2 二進制 3 Char 值 4 Base64 5 反向 如果需要把一段中文編碼請選擇UTF16&#xff0c;如果是英文就選擇UTF8。對于需要經常使用編碼切換的朋友是個好幫手。 也可以用來簡單加密&#xff1a;我們先在文本狀態下輸入一段不想讓別人知道或需要保密的文…

linkbox php,win10 docker-toolsbox 搭建php開發環境的教程

下載鏡像docker pull mysql:5.7docker pull php:7.2-fpmdocker pull nginxdocker pull redis:3.2設置共享文件宿主機創建目錄E:\wnmp\mysql57\confE:\wnmp\mysql57\logE:\wnmp\php72\confE:\wnmp\php72\confE:\wnmp\nginx\confE:\wnmp\nginx\confE:\wnmp\wwwvmware設置文件共享…

sublime text3:提示 There are no packages available installation 解決方案

純屬記錄&#xff0c;下次能找到解決。 第一步&#xff1a; 在sublime Text3界面按 ctrl 出現一個輸入框界面 第二步&#xff1a;在輸入框輸入&#xff1a; import urllib.request,os,hashlib; h eb2297e1a458f27d836c04bb0cbaf282 d0e7a3098092775ccb37ca9d6b2e4b7d; pf Pa…

如何提取幻燈片表格_如何查看對Google文檔,表格或幻燈片文件的最新更改

如何提取幻燈片表格The Google Suite offers you a handy way to view all the changes that have occurred in a file on Google Docs, Sheets, or Slides. This is extremely useful when you’ve made lots of changes to a file or are working as part of a team and need…

[20171130]關于rman的一些總結.txt

[20171130]關于rman的一些總結.txt --//最近一直做rman相關測試,測試那個亂,沒辦法.無法從周圍的人獲得幫助,純粹是自己的亂猜,亂測,不知道別人是否能看懂我寫的東西. --//有必要做一些總結,不一定對,僅僅是我當前的看法. 1.數據文件備份集中,文件頭是最后寫到備份集文件的. 2.…

支付寶紅包php,支付寶紅包賞金跳轉源碼,一鍵復制紅包碼,裂變推廣

[html]代碼庫支付寶到店紅包搜索碼跳轉推廣裂變-引流*{padding:0;margin:0;}.main{overflow: hidden;}a {color:black;}.main img{width:100%;outline-width:0px;vertical-align:top;}.main{position: relative;}.main .copy-container{width: 100%;height: 0.42rem;position: …

apt-get更新軟件包_如何使用Apt-fast加速軟件包下載和更新

apt-get更新軟件包By Default, Ubuntu uses apt-get to install packages and updates. Apt-get is a good tool but you can get much faster download speeds using Apt-Fast when downloading and updating your Ubuntu box. 默認情況下&#xff0c;Ubuntu使用apt-get安裝軟…

FallbackFactory啟動的時候拋出異常

在Hystrix做熔斷的時候&#xff0c;開始用的是FallBack&#xff0c;后來為了找出為啥exception&#xff0c;然后就用了FallBackFactory。但是奇怪的是&#xff0c;一起動就拋出異常&#xff0c;真的是百思不得騎姐&#xff0c;錯了其解。后來在github上找到了解答&#xff1a;h…

制作首頁的顯示列表

1. 在首頁添加顯示問答的列表&#xff0c;并定義好相應的樣式。 無序列表 <ul > <li>Coffee</li> <li>Tea</li> <li>Milk</li> </ul> {% block body %}<div class"container"><div class"row clearfi…

php xxtea加密,php - esp32和php XXTEA字符串加密 - SO中文參考 - www.soinside.com

輸入具有不同的數據類型可能會導致此問題&#xff0c;因為當前沒有任何類型或范圍檢查的XXTEA實現。或者它可能是由于所涉及的兩臺計算機的不同端序行為&#xff0c;因為二進制文件通常存儲為由字節構造的字數組。或者可能是由于缺少正式加密特定字符串和密鑰的官方或標準參考示…

ipad iphone開發_如何在iPad或iPhone上使用外部GPS設備

ipad iphone開發If you bought a Wi-Fi only iPad and now you wish you could use GPS with it, this is the guide for you. Follow along to hook your iPad up to an external GPS unit and/or GPS-enabled smartphone phone. 如果您購買了僅支持Wi-Fi的iPad&#xff0c;現…

jQuery系列(十四):jQuery中的ajax

1、什么是ajax AJAX 異步的javascript和XML&#xff08;Asynchronous Javascript and XML&#xff09; 簡言之&#xff0c;在不重載整個網頁的情況下&#xff0c;AJAX通過后臺加載數據&#xff0c;并在網頁上進行顯示。 通過 jQuery AJAX 方法&#xff0c;您能夠使用 HTTP Get…