ASP.NET Core使用MongoDB數據庫


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

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

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

創建 ASP.NET Core Mvc 項目

 

添加models,添加services

        基本的結構就這樣了

在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:

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

 

BaseService:

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:

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操作mongodb

 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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM