Skip to content

zhangxianchengvip/MongoDB.Driver.AspNetCore

Repository files navigation

MongoDBDriver.AspNetCore

简介

MongoDBDriver Asp.Net Core 服务注册

  1. 安装
Install-Package MongoDBDriver.AspNetCore
dotnet add package MongoDBDriver.AspNetCore
  1. 创建上下文类继承MongoDbContext
public class TestMongoDbContext : MongoDbContext
{
    //对应注册AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test")
    public TestMongoDbContext(string connectionString, string database) : base(connectionString, database)
    {
    }
    
	//对应注册AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test", options => {  })
    public TestMongoDbContext(string database, MongoClientSettings settings) : base(database, settings)
    {
    }
	//配置 MongoCollection
    public IMongoCollection<Doc> Doc => GetCollection<Doc>(nameof(Doc));
}
  1. 注册 MongoDBDriver.AspNetCore
builder.Services.AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test");
//OR
builder.Services.AddMongoDbContext<TestMongoDbContext>("mongodb://localhost:27017/", "Test", options => {  });
  1. 注入上下文
    private readonly TestMongoDbContext _context;
    public WeatherForecastController( TestMongoDbContext context)
    {
        _context = context;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public void Get()
    {
        //添加数据
        _context.Doc.InsertOne(new Doc { Title = "Test" });
    }

About

MongoDB Asp.Net Core Service registration

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages