ASP.NET Core使用MongoDB數據庫

環境:Asp.Net Core Mvc 2.2,MongoDB 4.09git

參考文檔:http://mongodb.github.io/mongo-csharp-driver/    http://mongodb.github.io/mongo-csharp-driver/2.8/    github

https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studioweb

建立 ASP.NET Core Mvc 項目

 

添加models,添加services

        基本的結構就這樣了mongodb

在models和services項目中安裝NuGet依賴庫:MongoDB.Driver    。 我安裝的最新版:2.8.1版本

Install-Package MongoDB.Driver -Version {VERSION}

添加實體模型類,添加對應的service操做類

 

BaseModel:數據庫

using System;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoDBDemo.Models
{
    public class BaseModel
    {
        [BsonId]        //標記主鍵
        [BsonRepresentation(BsonType.ObjectId)]     //參數類型  , 無需賦值
        public string Id { get; set; }

        [BsonElement(nameof(CreateDateTime))]   //指明數據庫中字段名爲CreateDateTime
        public DateTime CreateDateTime { get; set; }

        //[BsonElement(nameof(IsDelete))]
        public bool IsDelete { get; set; }

        public BaseModel()
        {
            CreateDateTime = DateTime.Now;
            IsDelete = false;
        }
    }
}

Student:json

namespace MongoDBDemo.Models
{
    public class Student : BaseModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

 

BaseService:api

using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using MongoDBDemo.Models;
using System.Collections.Generic;

namespace MongoDBDemo.Services
{
    public class BaseService<T> where T : BaseModel
    {
        private readonly IMongoCollection<T> _collection;   //數據表操做對象

        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tableName">表名</param>
        public BaseService(IConfiguration config, string tableName)
        {
            var client = new MongoClient(config.GetConnectionString("MongoDBDemo"));    //獲取連接字符串

            var database = client.GetDatabase(config.GetSection("MongoDBSetting:DBName").Value);   //數據庫名 (不存在自動建立)

            //獲取對特定數據表集合中的數據的訪問
            _collection = database.GetCollection<T>(tableName);     // (不存在自動建立)
        }
        
        //Find<T> – 返回集合中與提供的搜索條件匹配的全部文檔。
        //InsertOne – 插入提供的對象做爲集合中的新文檔。
        //ReplaceOne – 將與提供的搜索條件匹配的單個文檔替換爲提供的對象。
        //DeleteOne – 刪除與提供的搜索條件匹配的單個文檔。

        /// <summary>
        /// 獲取全部
        /// </summary>
        /// <returns></returns>
        public List<T> Get()
        {
            return _collection.Find(T => true).ToList();
        }

        /// <summary>
        /// 獲取單個
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public T Get(string id)
        {
            return _collection.Find<T>(T => T.Id == id).FirstOrDefault();
        }

        /// <summary>
        /// 建立
        /// </summary>
        /// <param name="T"></param>
        /// <returns></returns>
        public T Create(T T)
        {
            _collection.InsertOne(T);
            return T;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="TIn"></param>
        public void Update(string id, T TIn)
        {
            _collection.ReplaceOne(T => T.Id == id, TIn);
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="TIn"></param>
        public void Remove(T TIn)
        {
            _collection.DeleteOne(T => T.Id == TIn.Id);
        }

        /// <summary>
        /// 根據id刪除
        /// </summary>
        /// <param name="id"></param>
        public void Remove(string id)
        {
            _collection.DeleteOne(T => T.Id == id);
        }
    }
}

StudentService:app

using Microsoft.Extensions.Configuration;
using MongoDBDemo.Models;

namespace MongoDBDemo.Services
{
    public class StudentService : BaseService<Student>
    {
        public StudentService(IConfiguration config) : base(config, nameof(Student))
        {

        }
    }
}

 

配置文件 appsettings.json 加入函數

"ConnectionStrings": {
    "MongoDBDemo": "mongodb://localhost:27017" //鏈接字符串
  },
  "MongoDBSetting": {
    "DBName": "Test"
  },

 

上層寫好後,需在Web層Startup類中配置注入service注入以便在控制中使用service操做mongodbvisual-studio

 services.AddScoped<StudentService>();       //注入service服務

 

注入service後在控制器試一下好很差使,運行項目後是好使的

 

HomeController控制器代碼:

    public class HomeController : Controller
    {
        private readonly StudentService _studentService;
        public HomeController(StudentService studentService)                //構造函數注入
        {
            _studentService = studentService;
        }

        public IActionResult Index()
        {
            return View();
        }

        #region CRUD

        /// <summary>
        /// 獲取全部
        /// </summary>
        /// <returns></returns>
        public ActionResult<List<Student>> Get()
        {
            return _studentService.Get();
        }

        /// <summary>
        /// 根據id獲取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult<Student> Get(string id)
        {
            var Student = _studentService.Get(id);
            if (Student == null)
            {
                return NotFound();
            }
            return Student;
        }

        /// <summary>
        ///添加
        /// </summary>
        /// <param name="Student"></param>
        /// <returns></returns>
        public ActionResult<Student> Create(Student Student)
        {
            _studentService.Create(Student);
            return Ok();
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id"></param>
        /// <param name="StudentIn"></param>
        /// <returns></returns>
        public IActionResult Update(string id, Student StudentIn)
        {
            var Student = _studentService.Get(id);

            if (Student == null)
            {
                return NotFound();
            }
            _studentService.Update(id, StudentIn);
            return NoContent();
        }

        /// <summary>
        /// 刪除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public IActionResult Delete(string id)
        {
            var Student = _studentService.Get(id);

            if (Student == null)
            {
                return NotFound();
            }
            _studentService.Remove(Student.Id);
            return NoContent();
        }
        #endregion


        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }

 

試一下添加刪除,都是好使的:

 

 

 

 

 

 

完結。參考文檔:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-2.2&tabs=visual-studio

相關文章
相關標籤/搜索