温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在.net Core项目中连接MongoDB数据库

发布时间:2021-03-11 17:42:56 来源:亿速云 阅读:321 作者:Leah 栏目:开发技术

这期内容当中小编将会给大家带来有关怎么在.net Core项目中连接MongoDB数据库,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

方法如下:

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

怎么在.net Core项目中连接MongoDB数据库

怎么在.net Core项目中连接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");
  }
 }
 }
}

创建控制器

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";
}
<h3>Index</h3>
<h3>Index</h3>
<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里

怎么在.net Core项目中连接MongoDB数据库

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

怎么在.net Core项目中连接MongoDB数据库

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

怎么在.net Core项目中连接MongoDB数据库

添加省份代码如下:后端

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

<h3>Create</h3>
<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";
}
<h3>新增</h3>
<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数据库了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI