您好,登錄后才能下訂單哦!
這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān).net 中怎么連接MongoDB,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
連接MongoDB首先要通過(guò)Nuget添加一個(gè)MongoDB的包,下載此包
安裝完畢后開(kāi)始寫代碼了,創(chuàng)建一個(gè)省份實(shí)體,一個(gè)學(xué)校實(shí)體
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>
/// 省份里有多個(gè)學(xué)校 這里用集合保存
/// </summary>
public IList<School> SchoolName { get; set; }
}
}
namespace MongoCore.Models
{
//用于后面添加學(xué)校
public School(string schoolName, string years)
{
SchoolName = schoolName;
Years = years;
}
public class School
{
public string SchoolName { get; set; }
public string Years { get; set; }
}
}
創(chuàng)建上下文類,連接MongoDB
namespace MongoCore.Models
{
public class ProvinceContext
{
//定義數(shù)據(jù)庫(kù)
private readonly IMongoDatabase _database = null;
public ProvinceContext()
{
//連接服務(wù)器名稱 mongo的默認(rèn)端口27017
var client = new MongoClient("mongodb://.......:27017");
if (client != null)
//連接數(shù)據(jù)庫(kù)
_database = client.GetDatabase("數(shù)據(jù)庫(kù)名");
}
public IMongoCollection<Province> Province
{
get
{
return _database.GetCollection<Province>("Province");
}
}
}
}
創(chuàng)建控制器
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>
<a asp-action="Detail" asp-route-ProvinceID="@item.ProvinceID">詳 情</a>
<a asp-action="Delete" asp-route-ProvinceID="@item.ProvinceID">刪 除</a>
</td>
</tr>
}
</table>
運(yùn)行的時(shí)候修改配置在Startup.cs里
運(yùn)行效果是這樣的,現(xiàn)在還沒(méi)有數(shù)據(jù),
點(diǎn)擊新建按鈕添加省份,這里我添加了湖北省
添加省份代碼如下:后端
public IActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Province item)
{
try
{
//初始化學(xué)校類型數(shù)據(jù)
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>
接下來(lái)就是添加省份下面的學(xué)校了
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);
//添加學(xué)校
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">學(xué)校名稱</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>
然后添加學(xué)校,我添加了兩所學(xué)校,在MongoDB里可以看到數(shù)據(jù)
上述就是小編為大家分享的.net 中怎么連接MongoDB了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。