码迷,mamicode.com
首页 > 数据库 > 详细

.net core连接mongoDB

时间:2020-03-04 00:37:55      阅读:92      评论:0      收藏:0      [点我收藏+]

标签:获取   admin   条件   服务   ros   database   链接   inf   version   

技术图片

 

技术图片

 

 配置文件

{
"ConnectionStrings": {
"ConnectionString": "mongodb://admin:123456@192.168.1.6:27017",
"DatabaseName": "testdb"
}
}

 首先引用包

<PackageReference Include="Microsoft.Extensions.Configuration" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.2" />
<PackageReference Include="MongoDB.Driver" Version="2.10.2" />

CRUD 操作服务

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;

namespace MongoDbTestConsoleApp
{
    /// <summary>
    /// 官方 https://api.mongodb.com/csharp/2.2/html/R_Project_CSharpDriverDocs.htm
    ///  https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-mongo-app?view=aspnetcore-3.1&tabs=visual-studio
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T> where T : BaseModel
    {
        private readonly IMongoCollection<T> _collection;   //数据表操作对象

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="config"></param>
        /// <param name="tableName">表名</param>
        public BaseRepository(DatabaseSettings config, string tableName)
        {
            var client = new MongoClient(config.ConnectionString);    //获取链接字符串

            var database = client.GetDatabase(config.DatabaseName);

            //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);
        }
    }
}

  配置文件模型

using System;
using System.Collections.Generic;
using System.Text;

namespace MongoDbTestConsoleApp
{
    public class DatabaseSettings
    {
        public string ConnectionString { get; set; }
        public string DatabaseName { get; set; }
    }
}

  基础实体模型

using System;
using System.Collections.Generic;
using System.Text;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace MongoDbTestConsoleApp
{
    public class BaseModel
    {
        [BsonId]        //标记主键
        [BsonRepresentation(BsonType.ObjectId)]     //参数类型  , 无需赋值
        public string Id { get; set; }

        [BsonElement(nameof(AddTime))]   //指明数据库中字段名为CreateDateTime
        public DateTime AddTime { get; set; }

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

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

  测试模型

using System;
using System.Collections.Generic;
using System.Text;

namespace MongoDbTestConsoleApp
{
    public class StudentModel:BaseModel
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

  

 

.net core连接mongoDB

标签:获取   admin   条件   服务   ros   database   链接   inf   version   

原文地址:https://www.cnblogs.com/wangboy91/p/12405500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!