.net core 中使用MongoDB

https://www.thecodebuzz.com/exception-filters-in-net-core/

https://www.mongodb.com/docs/drivers/csharp/

https://www.mongodb.com/developer/languages/csharp/create-restful-api-dotnet-core-mongodb/

  1. 安装依赖的包
    在这里插入图片描述
  2. 定义服务接口
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MongoDBHelper.Helper
{
    public interface IMongoDB<T> where T : class
    {


        Task InsertOne(T document);


        Task InsertMany(List<T> documents);


        Task<long> BulkInsert(List<T> documents);


        Task<UpdateResult> UpdateOne(string name, string id);


        Task<UpdateResult> UpdateMultiFields(T document, string id);


        Task Inc(string id);


        Task<List<T>> GetAll();


        Task<T> GetOneByID(string id);
    }
}

  1. 定义实体类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

namespace MongoDBHelper.Model
{
    public class Person
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string? Id { get; set; }
		
		//我们系统里这个字段名称是Age。但是MongoDB存的是age
        [BsonElement("age")]
        [JsonPropertyName("age")]
        public int Age { get; set; }

        [BsonElement("name")]
        [JsonPropertyName("name")]
        public string Name { get; set; }

		//系统以及MongoDB里都是address
        public string address { get; set; }
		//这个字段不会存到MongoDB中
        [BsonIgnore]
        public string IgnoreField { get; set; }
    }
}

  1. 定义helper 类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Driver;
using Microsoft.Extensions.Options;
using MongoDBHelper.Model;
using MongoDB.Bson;

namespace MongoDBHelper.Helper
{
    public class MongoDBTools<T>: IMongoDB<T> where T : Person
    {
        public readonly IMongoCollection<T> mongoCollection;

        public IOptionsSnapshot<Config> _config;
        
        public MongoDBTools(IOptionsSnapshot<Config> config)
        {
            _config = config;
            MongoClient client = new MongoClient(config.Value.connectstring);

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

            mongoCollection = database.GetCollection<T>(config.Value.collection);
        }

        public Task InsertOne(T document)
        {
            return mongoCollection.InsertOneAsync(document);
        }

        public Task InsertMany(List<T> documents)
        {
            return mongoCollection.InsertManyAsync(documents,new InsertManyOptions() { IsOrdered=false});
        }


        //批量插入,忽略排序
        //默认是不忽略排序的,以这种方式插入数据,假如中间的失败了,则以后的也不再插入
        //取消默认排序后,即使中间又失败的数据,后续数据也会继续插入

        public async Task<long> BulkInsert(List<T> documents)
        {
            try
            {
                List<WriteModel<T>> values = new List<WriteModel<T>>();

                foreach (var item in documents)
                {
                    values.Add(new InsertOneModel<T>(item));
                }
                return mongoCollection.BulkWriteAsync(documents.Select(x => new InsertOneModel<T>(x)).ToList(), new BulkWriteOptions() { IsOrdered = true }).Result.InsertedCount;
            }
            catch (Exception)
            {
                Exception exception = new Exception("批量插入失败");
                throw exception;
            }
            
        }

        public Task<UpdateResult> UpdateOne(string name,string id)
        {
            UpdateDefinition<T> update = Builders<T>.Update.AddToSet<string>("name", name);
            return mongoCollection.UpdateOneAsync(Builders<T>.Filter.Eq("Id",id), update);
        }


        public Task<UpdateResult> UpdateMultiFields(T document,string id)
        {
            UpdateDefinition<T> updateDefinition = Builders<T>.Update.Set(x => x.Name, document.Name).Set(x=>x.Age,document.Age);

            return mongoCollection.UpdateOneAsync(Builders<T>.Filter.Eq("Id", id), updateDefinition);

        }


        public Task Inc(string id)
        {
            FilterDefinition<T> filterDefinition = Builders<T>.Filter.Eq("Id", id);

            UpdateDefinition<T> updateDefinition = Builders<T>.Update.Inc("Age", 1);

            return mongoCollection.UpdateOneAsync(filterDefinition, updateDefinition);
        }


        public async Task<List<T>> GetAll()
        {
            return await mongoCollection.FindSync(new BsonDocument()).ToListAsync();
        }

        public Task<T> GetOneByID(string id)
        {
            return mongoCollection.Find(Builders<T>.Filter.Eq("Id",id)).FirstOrDefaultAsync();
        }
    }
}


  1. 定义controller
using Microsoft.AspNetCore.Mvc;
using MongoDBHelper.Helper;
using MongoDBHelper.Model;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace CoreMongoDB.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class MongoDB : ControllerBase
    {
        public readonly IMongoDB<Person> _mongoDBTools;

        public MongoDB(IMongoDB<Person> mongoDBTools)
        {
            _mongoDBTools = mongoDBTools;
        }

        [HttpPost]
        public async Task<bool> InsertOne([FromBody] Person person)
        {
            await _mongoDBTools.InsertOne(person);

            return true;
        }


        [HttpGet]
        public Task<List<Person>> ListAll()
        {
            return _mongoDBTools.GetAll();
        }


        [HttpGet]
        public Task<Person> GetByID([FromQuery] string id)
        {
            return _mongoDBTools.GetOneByID(id);
        }

        [HttpPost]
        public async Task<long> BulkInsert([FromBody] List<Person> persons)
        {
            return await _mongoDBTools.BulkInsert(persons);
        }

        [HttpPut]
        public long UpdateMultiFields([FromBody] Person person,[FromQuery] string id)
        {
            return   _mongoDBTools.UpdateMultiFields(person, id).Result.ModifiedCount;

        }
    }
}

  1. 定义全局异常filter
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace CoreMongoDB.Exception
{
    public class ExceptionHandler : IAsyncExceptionFilter
    {
        public Task OnExceptionAsync(ExceptionContext context)
        {
            string message = context.Exception.Message;
            ObjectResult objectResult = new ObjectResult(new { code = 500, msg = message });

            //Logs your technical exception with stack trace below
            context.Result = objectResult;
            return Task.CompletedTask;
        }
    }
}

  1. 依赖注入
builder.Services.Configure<Config>(
    builder.Configuration.GetSection("MongoDBConfig"));

builder.Services.AddScoped<Config>();


builder.Services.AddScoped(typeof(IMongoDB<>),typeof(MongoDBTools<>));

builder.Services.Configure<MvcOptions>(opt =>
{
    opt.Filters.Add<ExceptionHandler>();
});

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
随着时代的进步,数据库已经成为了应用程序开发不可或缺的一部分。因此,如何操作数据库已经成为了开发者们需要掌握的技能。.NET Core是一个全新的跨平台的开发框架,其在数据库开发方面也取得了很大的突破,提供了许多方便开发者进行数据库操作的方式。 . NET Core现在支持许多常用的数据库,包括MySQL、PostgreSQL、SQL Server和SQLite等。这些数据库可以运行在Windows、Linux和Mac OS等常见的操作系统上。 在进行数据库开发时,首先需要选择适合开发的数据库驱动程序。.NET Core有许多不同的驱动程序,每个驱动程序可以让你通过特定的连接字符串进行连接到数据库。例如,使用Microsoft.EntityFrameworkCore.SqlServer驱动程序来连接SQL Server数据库。 有了连接数据库的驱动程序之后,就可以使用.NET Core提供的多种方式来进行数据库操作。例如,使用ADO.NET进行数据库操作。ADO.NET.NET Core用于创建和执行数据库查询的框架。你可以使用ADO.NET执行常规的SQL查询、存储过程和批处理操作。 此外,.NET Core还提供了Entity Framework Core,它是一个ORM (Object-Relational Mapping)框架,可以轻松地将对象映射到关系数据库的表。通过Entity Framework Core,你可以通过LINQ语句非常方便地进行数据库操作。 除了以上两种方式之外,.NET Core还提供了其他的一些便捷数据库操作方式,例如使用Dapper进行ORM(对象关系映射)操作、使用MongoDB Driver进行连接MongoDB数据库等。 总的来说,.NET Core提供了丰富的数据库操作方式,开发者可以根据自己的需要选择合适的方式进行开发。这些方式可以使得开发者更快速创建和维护应用程序,大大缩短了开发周期。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值