NET Core Connection MongoDB

Source: Internet
Author: User

Two days ago in learning MongoDB related knowledge, did a small demo, do is the province below how many schools, well, do more rough ...

Connect MongoDB first to add a MongoDB package through NuGet, download this package

Start writing code after installation, create a province entity, 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>///The provinces have multiple schools here to save/// </summary> public ilist<school> Schoolname {get; set;}}} Namespace mongocore.models{
Used to add school later
Public School (String schoolname, String years)
{
Schoolname = Schoolname;
years = years;
Public class School {public string Schoolname {get; set;} string Years {get; set;} }}

Create context class, connect MongoDB

namespace mongocore.models{public    class Provincecontext    {        //define Database        private ReadOnly Imongodatabase _ Database = null;        Public Provincecontext ()        {            ///connection server name  MONGO default port 27017            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 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<mongocore.models.province>@{viewdata["Title"] = "Index";} 

When running, modify the configuration in Startup.cs.

The effect is this, and now there is no data,

Click the New button Add province, here I added Hubei province

Add the province code as follows: Back end

   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";} 

The next step is to add the school below 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 prov Inceid, 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";} 

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

NET Core Connection MongoDB

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.