ASP.NET Core3.1 中使用MongoDB基本操作


1、安裝驅動包

  

install-package  MongoDB.Driver -version 2.11.7

 

2、配置文件幫助類 ConfigHelper

 

 public static class ConfigHelper
    {
        private static IConfiguration _configuration;

        static ConfigHelper()
        {
            //在當前目錄或者根目錄中尋找appsettings.json文件
            string fileName = "appsettings.json";

            string directory = AppContext.BaseDirectory;
            directory = directory.Replace("\\", "/");

            string filePath = $"{directory}/{fileName}";
            if (!File.Exists(filePath))
            {
                var length = directory.IndexOf("/bin");
                filePath = $"{directory.Substring(0, length)}/{fileName}";
            }

            var builder = new ConfigurationBuilder().AddJsonFile(filePath, false, true);
            _configuration = builder.Build();

        }

        public static string GetSectionValue(string key)
        {
            return _configuration.GetSection(key).Value;
        }

    }

 

 

3、appsettings.json配置

 

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",

  "MongoDBAddress": "mongodb://192.168.0.161:27017", //連接字符串
  "MongoDBName": "local" //集合名
}

 

 

4、實體類

 

    /// <summary>
    /// 公共實體類
    /// </summary>
    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;
        }
    }

 


namespace MongodbDemo.Models
{

  public class Student : BaseModel
  {

     public string Name { get; set; }
     public int Age { get; set; }

     List<Course> _courses = new List<Course>();
     public virtual List<Course> Courses { get { return _courses; } set { _courses = value; } }
  }

  public class Course
  {

     public string StudentId { get; set; }
     public string Name { get; set; }

  }

 

}

 

5、業務基礎類

namespace MongodbDemo.Services
{
    /// <summary>
    /// 業務基礎類
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseMongoDbService<T> where T : BaseModel
    {
        protected readonly IMongoCollection<T> _collection;   //數據表操作對象

        /// <summary>
        /// 構造函數
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tableName">表名</param>
        public BaseMongoDbService(string tableName)
        {
            var client = new MongoClient(ConfigHelper.GetSectionValue("MongoDBAddress"));    //獲取鏈接字符串
            var database = client.GetDatabase(ConfigHelper.GetSectionValue("MongoDBName"));   //數據庫名 (不存在自動創建)
            _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 Add(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>
        /// 根據id刪除
        /// </summary>
        /// <param name="id"></param>
        public void Remove(string id)
        {
            _collection.DeleteOne(T => T.Id == id);
        }
    }
}

 

6、調用方式

      StudentService _studentService = new StudentService();
        public void Test()
        {

            Student _students = new Student();
            _students.Name = "張三";
            _students.Age = 10;
            Course _course = new Course();
            _course.StudentId = _students.Id;
            _course.Name = "數學";
            _students.Courses.Add(_course);
            _studentService.Add(_students);
       }

 

 

 


免責聲明!

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



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