欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET Core使用MongoDB数据库

程序员文章站 2022-06-19 17:59:21
环境: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 ......

环境:asp.net core mvc 2.2,mongodb 4.09

参考文档:        

创建 asp.net core mvc 项目

 ASP.NET Core使用MongoDB数据库

添加models,添加services

ASP.NET Core使用MongoDB数据库        基本的结构就这样了

在models和services项目中安装nuget依赖库:mongodb.driver    。 我安装的最新版:2.8.1版本

install-package mongodb.driver -version {version}

ASP.NET Core使用MongoDB数据库

添加实体模型类,添加对应的service操作类

ASP.NET Core使用MongoDB数据库

 

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))
        {

        }
    }
}

 

上层写好后,需在web层startup类中配置注入service注入以便在控制中使用service操作mongodb

 services.addscoped<studentservice>();       //注入service服务

ASP.NET Core使用MongoDB数据库

 

注入service后在控制器试一下好不好使,运行项目后是好使的

ASP.NET Core使用MongoDB数据库

 

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

 

试一下添加删除,都是好使的:

ASP.NET Core使用MongoDB数据库ASP.NET Core使用MongoDB数据库

 

 

 

 

 

 

完结。参考文档: