.net Core连接MongoDB数据库的步骤详解

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了.net Core连接MongoDB数据库的步骤详解脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前言

前两天在学习MongoDB相关的知识,做了个小Demo,做的是省份下面有多少所学校,嗯,做的比较粗暴。。。

我们在MongoDB的官方文档中看到,MongoDb的2.4以上的For .Net的驱动是支持.Net Core 2.0的。

所以,在我们安装好了MangoDB后,就可以开始MangoDB的.Net之旅了。

方法如下:

连接MongoDB首先要通过Nuget添加一个MongoDB的包,下载此包

安装完毕后开始写代码了,创建一个省份实体,一个学校实体

using MongoDB.Bson.Serialization.Attributes;using System.Collections.Generic;
@R_406_1507@pace 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");
  }
 }
 }
}

创建控制器

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>&amp;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里

运行效果是这样的,现在还没有数据,

点击新建按钮添加省份,这里我添加了湖北省

添加省份代码如下:后端

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里可以看到数据

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本宝典的支持。

脚本宝典总结

以上是脚本宝典为你收集整理的.net Core连接MongoDB数据库的步骤详解全部内容,希望文章能够帮你解决.net Core连接MongoDB数据库的步骤详解所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:.netasp.net