.net Core鏈接MongoDB

前兩天在學習MongoDB相關的知識,作了個小Demo,作的是省份下面有多少所學校,嗯,作的比較粗暴。。。mongodb

鏈接MongoDB首先要經過Nuget添加一個MongoDB的包,下載此包數據庫

安裝完畢後開始寫代碼了,建立一個省份實體,一個學校實體後端

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> /// 省份裏有多個學校 這裏用集合保存 /// </summary> public IList<School> SchoolName { get; set; } } } namespace MongoCore.Models {
//用於後面添加學校
 public School(string schoolName, string years)
        {
            SchoolName = schoolName;
            Years = years;
        }
public class School { public string SchoolName { get; set; } public string Years { get; set; } } }

建立上下文類,鏈接MongoDB服務器

namespace MongoCore.Models
{
    public class ProvinceContext
    {
        //定義數據庫
        private readonly IMongoDatabase _database = null;

        public ProvinceContext()
        {
            //鏈接服務器名稱  mongo的默認端口27017
            var client = new MongoClient("mongodb://.......:27017");
            if (client != null)
                //鏈接數據庫
                _database = client.GetDatabase("數據庫名");
        }

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

建立控制器async

  private readonly ProvinceContext _context = new ProvinceContext();
        public async Task<IActionResult> Index()
        {
            var list = await _context.Province.Find(_ => true).ToListAsync();
            return View(list);
        }

視圖學習

@model List<MongoCore.Models.Province>
@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>
<h2>Index</h2>
<a asp-action="Create"><input type="button" value="新 建" class="btn btn-default" /></a>
<table class="table">
    <tr>
        <th>省份ID</th>
        <th>省份名稱</th>
        <th>操做</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">新 增</a>&nbsp;&nbsp;
                <a asp-action="Detail" asp-route-ProvinceID="@item.ProvinceID">詳 情</a>&nbsp;&nbsp;
                <a asp-action="Delete" asp-route-ProvinceID="@item.ProvinceID">刪 除</a>&nbsp;&nbsp;
            </td>
        </tr>
    }
</table>

運行的時候修改配置在Startup.cs裏spa

運行效果是這樣的,如今尚未數據,code

點擊新建按鈕添加省份,這裏我添加了湖北省orm

添加省份代碼以下:後端blog

   public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create(Province item)
        {
            try
            {
                
                //初始化學校類型數據
                item.SchoolName = new List<School>();
                
                await _context.Province.InsertOneAsync(item);
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

視圖:

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

<h2>Create</h2>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label class="control-label">省份ID</label>
                <input asp-for="ProvinceID" class="form-control" />
            </div>
            <div class="form-group">
                <label class="control-label">省份名稱</label>
                <input asp-for="ProvinceName" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="保 存" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

接下來就是添加省份下面的學校了

  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);
            //添加學校
            item.SchoolName.Add(sl);
            //更新
            ReplaceOneResult actionResult
               = await _context.Province
                               .ReplaceOneAsync(n => n.ProvinceID.Equals(ProvinceID)
                                       , item
                                       , new UpdateOptions { IsUpsert = true });
            return RedirectToAction(nameof(Index));
        }

視圖:

@model MongoCore.Models.Province
@{
    ViewData["Title"] = "Insert";
}
<h2>新增</h2>
<div class="row">
    <div class="col-md-4">
        <form asp-action="Insert">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="ProvinceID" />
            <div class="form-group">
                <label class="control-label">學校名稱</label>
                <input name="SchoolName" class="form-control" />
            </div>
            <div class="form-group">
                <label class="control-label">成立年份</label>
                <input name="Years" class="form-control" />
            </div>
            <div class="form-group">
                <input type="submit" value="保 存" class="btn btn-default" />
            </div>
        </form>
    </div>
</div>

而後添加學校,我添加了兩所學校,在MongoDB裏能夠看到數據

相關文章
相關標籤/搜索