Detailed steps for. net Core to connect to the MongoDB database, coremongodb
Preface
I learned MongoDB-related knowledge two days ago and made a small Demo, which is about the number of schools in the province. Well, it's rough...
As we can see in the official documents of MongoDB, over 2.4 of MongoDb's For. Net drivers support. Net Core 2.0.
Therefore, after we have installed MangoDB, we can start the. Net tour of MangoDB.
The method is as follows:
To connect to MongoDB, you must first add a MongoDB package through Nuget and download this package.
After the installation is complete, write the code to create a province entity and a school entity.
Using MongoDB. bson. serialization. attributes; using System. collections. generic; namespace using core. models {public class Province {[BsonId] public int ProvinceID {get; set;} public string ProvinceName {get; set ;} /// <summary> /// multiple schools in the province are saved in a set. // </summary> public IList <School> SchoolName {get; set ;}}} namespace using core. models {// used to add the School public School (string schoolName, string years) {SchoolName = schoolName; Years = years;} public class School {public string SchoolName {get; set ;} public string Years {get; set ;}}}
Create a context class to connect to MongoDB
Namespace using core. models {public class ProvinceContext {// defines the database private readonly IMongoDatabase _ database = null; public ProvinceContext () {// The default port of the connection server name mongo is 27017 var client = new MongoClient ("mongodb ://.......: 27017 "); if (client! = Null) // connect to the database _ database = client. getDatabase ("database Name");} public IMongoCollection <Province> Province {get {return _ database. getCollection <Province> ("Province ");}}}}
Create a controller
private readonly ProvinceContext _context = new ProvinceContext(); public async Task<IActionResult> Index() { var list = await _context.Province.Find(_ => true).ToListAsync(); return View(list); }
View
@ Model List <javascore. models. province >@{ ViewData ["Title"] = "Index ";}
Modify the configuration in Startup. cs during running.
The running effect is as follows, and no data is available now,
Click Create to add a province.
The code for adding a province is as follows: backend
Public IActionResult Create () {return View ();} [HttpPost] [ValidateAntiForgeryToken] public async Task <ActionResult> Create (Province item) {try {// initialize the school type data item. schoolName = new List <School> (); await _ context. province. insertOneAsync (item); return RedirectToAction (nameof (Index) ;}catch {return View ();}}
View:
@ Model core. models. province @ {ViewData ["Title"] = "Create ";}
The next step is to add schools under the province.
Public async Task <IActionResult> Insert (int ProvinceID) {var num = await _ context. province. find (p => p. provinceID = ProvinceID ). singleOrDefaultAsync (); return View (num);} [HttpPost] [ValidateAntiForgeryToken] public async Task <IActionResult> Insert (int ProvinceID, string Years, string SchoolName) {var item = await _ context. province. find (p => p. provinceID = ProvinceID ). singleOrDefaultAsync (); School sl = new School (SchoolName, Years); // Add School item. schoolName. add (sl); // update ReplaceOneResult actionResult = await _ context. province. replaceOneAsync (n => n. provinceID. equals (ProvinceID), item, new UpdateOptions {IsUpsert = true}); return RedirectToAction (nameof (Index ));}
View:
@ Model core. models. province @ {ViewData ["Title"] = "Insert ";}
Then add the school. I have added two schools and you can see the data in MongoDB.
Summary
The above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.