Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to connect MongoDB in .net

Shulou Source: shulou.com Published: 2022-06-02 06:38:10 09月15日 Update

In this issue, the editor will bring you about how to connect to MongoDB in. Net. The article is rich in content and analyzes and narrates it from a professional point of view. I hope you can get something after reading this article.

The first step to connect to MongoDB is to add a MongoDB package through Nuget, and download this package

After the installation, we began to write code to create a provincial 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;}

/ / /

/ / there are many schools in the province that are saved here with collections.

/ / /

Public IList SchoolName {get; set;}

}

}

Namespace MongoCore.Models

{

/ / used to add schools later

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 MongoCore.Models

{

Public class ProvinceContext

{

/ / define the database

Private readonly IMongoDatabase _ database = null

Public ProvinceContext ()

{

/ / default port 27017 of the connection server name mongo

Var client = new MongoClient ("mongodb://.:27017")

If (client! = null)

/ / Connect to the database

_ database = client.GetDatabase ("database name")

}

Public IMongoCollection Province

{

Get

{

Return _ database.GetCollection ("Province")

}

}

}

}

Create a controller

Private readonly ProvinceContext _ context = new ProvinceContext ()

Public async Task Index () {

Var list = await _ context.Province.Find (_ = > true). ToListAsync (); return View (list);}

View

@ model List

@ {

ViewData ["Title"] = "Index"

}

Index

Index

Provincial ID

Name of province

Operation

@ foreach (var item in Model)

{

@ Html.DisplayFor (modelItem = > item.ProvinceID)

@ Html.DisplayFor (modelItem = > item.ProvinceName)

Newly added

Detailed situation

Delete

}

Modify the configuration at run time in Startup.cs

It works like this, and there is no data yet.

Click the New button to add provinces, here I added Hubei Province

Add the province code as follows: backend

Public IActionResult Create ()

{

Return View ()

}

[HttpPost]

[ValidateAntiForgeryToken]

Public async Task Create (Province item)

{

Try

{

/ / initialize school type data

Item.SchoolName = new List ()

Await _ context.Province.InsertOneAsync (item)

Return RedirectToAction (nameof (Index))

}

Catch

{

Return View ()

}

}

View:

@ model MongoCore.Models.Province

@ {

ViewData ["Title"] = "Create"

}

Create

Provincial ID

Name of province

The next step is to add schools under the provinces.

Public async Task Insert (int ProvinceID)

{

Var num = await _ context.Province.Find (p = > p.ProvinceID = = ProvinceID) .SingleOrDefaultAsync ()

Return View (num)

}

[HttpPost]

[ValidateAntiForgeryToken]

Public async Task 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 a 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"

}

Add

Name of the school

Year of establishment

Then add schools, I added two schools, you can see the data in MongoDB

The above is the editor for you to share. Net how to connect MongoDB, if you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.

Tags: School province data name database view code content entity that is analysis run next up and down context major small and medium rich in content multiple years Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Apple Redmi OPPO Reno Xiaomi