介紹
在本文中,我們將學習如何使用ASP.NET CORE去實現MongoDB的CRUD操作。MongoDB是一個NO SQL的資料庫。與SQLServer相比,它的優勢在於可伸縮性和靈活性,然而,這些並不是資料庫MongoDB所具有的唯一可取之處。
步驟1
首先,我們將使用Nuget命令在Visual Studio中新增mongodb資料庫
Install-Package MongoDB.Driver -Version 2.11.6
步驟2
登入mongodb
https://www.mongodb.com/
登入後建立叢集,如果已經建立了一個叢集,則不要建立叢集
建立集群后,單擊Connect
單擊連線後,單擊連線應用程式
之後,您將找到連線字串。
選擇驅動器C#.NET,對於版本,我使用的是2.11.6,所以選擇2.11或更高版本。
第3步
現在我們來到visualstudio。建立ASP.NET Core Web應用
第4步
建立專案後,轉到appsettings.json檔案並設定連線字串。
{ "MyKey": "mongodb+srv://ajay:<Password>@cluster0.qmqmt.mongodb.net/<Databasename>?retryWrites=true&w=majority", "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" } }, "AllowedHosts": "*" }
在上面的MYKEY中,您需要輸入您的資訊並更改密碼和資料庫。
請注意
如果資料庫已經建立,那麼它就在工作,但是如果資料庫還沒有建立,那麼它就會自動建立。
第5步
現在我們來看看控制器:
public HomeController(IConfiguration Configuration) { Client = new MongoClient(Configuration["MyKey"]); DB = Client.GetDatabase("Your Database"); }
您可以設定資料庫名稱,即連線字串。
第6步
現在建立一個類:
public class CarModel { public ObjectId Id { get; set; } public string Empname { get; set; } public string Empemail { get; set; } public string Phoneno { get; set; } public string state { get; set; } }
在上面的類中,ObjectId是自動建立的Bson ID,您可以使用
using MongoDB.Bson;
第7步 - 插入資料
[HttpPost] public IActionResult Index(CarModel model) { var collection = DB.GetCollection < CarModel > ("EmployeeDetails"); collection.InsertOne(model); return View(); }
第8步 - 編輯和更新資料
編輯
public ActionResult Edit(string id) { if (ModelState.IsValid) { var collection = DB.GetCollection < CarModel > ("EmployeeDetails").Find(Builders < CarModel > .Filter.Eq("Id", ObjectId.Parse(id))).SingleOrDefault(); return View(collection); } return View(); }
更新
[HttpPost] public ActionResult Edit(CarModel model, string Id) { var collection = DB.GetCollection < CarModel > ("EmployeeDetails"); var update = collection.FindOneAndUpdateAsync(Builders < CarModel > .Filter.Eq("Id", ObjectId.Parse(Id)), Builders < CarModel > .Update.Set("Empname", model.Empname).Set("Empemail", model.Empemail)); return RedirectToAction("About"); }
在上面的編輯中,您將在ID引數中傳入當前ID。
第9步
顯示資料
public ActionResult Show() { var collection = DB.GetCollection < CarModel > ("EmployeeDetails").Find(new BsonDocument()).ToList(); return View(collection); }
摘要
在本文中,我們學習了使用ASP.NET Core和MongoDB。本文讓您基本瞭解如何將MongoDB與ASP.NET Core應用程式。
最新評論