Detailed steps of. Net core connecting to mongodb database

Time:2020-2-16

Preface

Two days ago, I studied mongodb related knowledge and made a small demo. What I did was how many schools are there under the province. Well, it was rough…

We can see in the official documents of mongodb that the drivers of mongodb for. Net above 2.4 support. Net core 2.0.

So, after we have installed mangodb, we can start the. Net tour of mangodb.

The method is as follows:

To connect mongodb, first add a mongodb package through nuget and download the package

After installation, start to write code, create a province entity and a school entity

using MongoDB.Bson.Serialization.Attributes;using System.Collections.Generic;
namespace MongoCore.Models
{
 public class Province
 {
 [BsonId]
 public int ProvinceID { get; set; }

 public string ProvinceName { get; set; }
 /// <summary>
 ///There are many schools in the province, which are stored in collections
 /// </summary>
 public IList<School> SchoolName { get; set; }
 }
}

namespace MongoCore.Models
{// used to add public school (string schoolname, string years) {schoolname = schoolname; years = years;}
 public class School
 {
 public string SchoolName { get; set; }
 public string Years { get; set; }
 }
}

Create context class, connect mongodb

namespace MongoCore.Models
{
 public class ProvinceContext
 {
 //Define database
 private readonly IMongoDatabase _database = null;
 public ProvinceContext()
 {
  //Connect to default port 27017 of server name Mongo
  var client = new MongoClient("mongodb://.......:27017");
  if (client != null)
  //Connect to database
  _Database = client.getdatabase ("database name");
 }

 public IMongoCollection<Province> Province
 {
  get
  {
  return _database.GetCollection<Province>("Province");
  }
 }
 }
}

Create 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<MongoCore.Models.Province>
@{
 ViewData["Title"] = "Index";
}
<h2>Index</h2>
<h2>Index</h2>
< a ASP action = "create" > < input type = "button" value = "new" / ></a>
<table>
 <tr>
 < th > province ID < / th >
 < th > province name < / th >
 < th > operation < / th >
 </tr>
 @foreach (var item in Model)
 {
 <tr>
  <td>
  @Html.DisplayFor(modelItem => item.ProvinceID)
  </td>
  <td>
  @Html.DisplayFor(modelItem => item.ProvinceName)
  </td>
  <td>
  < a ASP action = "insert" ASP route provinceid = "@ item. Provinceid" > New</a>  
  < a ASP action = "detail" ASP route provinceid = "@ item. Provinceid" > details</a>  
  < a ASP action = "delete" ASP route provinceid = "@ item. Provinceid" > delete</a>  
  </td>
 </tr>
 }
</table>

When running, modify the configuration in startup.cs

The running effect is like this. There is no data yet,

Click the new button to add a province. Here I add Hubei Province

Add province code as follows: backend

public IActionResult Create()
 {
  return View();
 }
 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<ActionResult> Create(Province item)
 {
  try
  {
  //Initialize school type data
  item.SchoolName = new List<School>();
  await _context.Province.InsertOneAsync(item);
  return RedirectToAction(nameof(Index));
  }
  catch
  {
  return View();
  }
 }

View:

@model MongoCore.Models.Province
@{
 ViewData["Title"] = "Create";
}

<h2>Create</h2>
<div>
 <div>
 <form asp-action="Create">
  <div asp-validation-summary="ModelOnly"></div>
  <div>
  < label > province ID < / label >
  <input asp-for="ProvinceID" />
  </div>
  <div>
  < label > name of province < / label >
  <input asp-for="ProvinceName" />
  </div>
  <div>
  < input type = "submit" value = "save" / >
  </div>
 </form>
 </div>
</div>

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 MongoCore.Models.Province
@{
 ViewData["Title"] = "Insert";
}
<h2>New</h2>
<div>
 <div>
 <form asp-action="Insert">
  <div asp-validation-summary="ModelOnly"></div>
  <input type="hidden" asp-for="ProvinceID" />
  <div>
  < label > school name < / label >
  <input name="SchoolName" />
  </div>
  <div>
  < label > year of establishment < / label >
  <input name="Years" />
  </div>
  <div>
  < input type = "submit" value = "save" / >
  </div>
 </form>
 </div>
</div>

Then add schools. I added two schools. You can see the data in mongodb

summary

The above is the whole content of this article. I hope that the content of this article has a certain reference learning value for everyone’s study or work. If you have any questions, you can leave a message and exchange. Thank you for your support for developepaar.