ASP.NET Core Web API和MongoDB与多个集合
创始人
2024-09-15 14:00:26
0

以下是一个使用ASP.NET Core Web API和MongoDB的示例代码,该代码可以与多个集合进行交互:

首先,确保你已经安装了MongoDB.DriverMongoDB.Driver.Core NuGet包。

接下来,创建一个名为MongoDbContext的类,该类继承自IMongoDbContext接口,并实现所需的方法。这个类将用于与MongoDB进行交互。

using MongoDB.Driver;

public class MongoDbContext : IMongoDbContext
{
    private readonly IMongoDatabase _database;
    
    public MongoDbContext(string connectionString, string databaseName)
    {
        var client = new MongoClient(connectionString);
        _database = client.GetDatabase(databaseName);
    }
    
    public IMongoCollection GetCollection(string collectionName)
    {
        return _database.GetCollection(collectionName);
    }
}

然后,创建一个名为WeatherForecast的简单模型类,用于示例。

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

public class WeatherForecast
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
    
    public string Location { get; set; }
    
    public DateTime Date { get; set; }
    
    public int Temperature { get; set; }
}

接下来,创建一个名为WeatherForecastRepository的类,该类将使用MongoDbContext与MongoDB集合进行交互。

public class WeatherForecastRepository : IWeatherForecastRepository
{
    private readonly IMongoCollection _collection;
    
    public WeatherForecastRepository(IMongoDbContext dbContext)
    {
        _collection = dbContext.GetCollection("WeatherForecasts");
    }
    
    public async Task> GetAll()
    {
        var result = await _collection.Find(_ => true).ToListAsync();
        return result;
    }
    
    public async Task GetById(string id)
    {
        var filter = Builders.Filter.Eq(f => f.Id, id);
        var result = await _collection.Find(filter).FirstOrDefaultAsync();
        return result;
    }
    
    public async Task Create(WeatherForecast weatherForecast)
    {
        await _collection.InsertOneAsync(weatherForecast);
    }
    
    public async Task Update(string id, WeatherForecast weatherForecast)
    {
        var filter = Builders.Filter.Eq(f => f.Id, id);
        await _collection.ReplaceOneAsync(filter, weatherForecast);
    }
    
    public async Task Delete(string id)
    {
        var filter = Builders.Filter.Eq(f => f.Id, id);
        await _collection.DeleteOneAsync(filter);
    }
}

最后,在你的控制器中使用WeatherForecastRepository进行数据访问。

[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly IWeatherForecastRepository _repository;
    
    public WeatherForecastController(IWeatherForecastRepository repository)
    {
        _repository = repository;
    }
    
    [HttpGet]
    public async Task GetAll()
    {
        var result = await _repository.GetAll();
        return Ok(result);
    }
    
    [HttpGet("{id}")]
    public async Task GetById(string id)
    {
        var result = await _repository.GetById(id);
        if (result == null)
        {
            return NotFound();
        }
        
        return Ok(result);
    }
    
    [HttpPost]
    public async Task Create(WeatherForecast weatherForecast)
    {
        await _repository.Create(weatherForecast);
        return CreatedAtAction(nameof(GetById), new { id = weatherForecast.Id }, weatherForecast);
    }
    
    [HttpPut("{id}")]
    public async Task Update(string id, WeatherForecast weatherForecast)
    {
        await _repository.Update(id, weatherForecast);
        return NoContent();
    }
    
    [HttpDelete("{id}")]
    public async Task Delete(string id)
    {
        await _repository.Delete(id);
        return NoContent();
    }
}

这就是一个使用ASP.NET Core Web API和MongoDB与多个集合进行交互的示例。你可以根据自己的需求进行修改和扩展。

相关内容

热门资讯

避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
安装了Anaconda之后找不... 在安装Anaconda后,如果找不到Jupyter Notebook,可以尝试以下解决方法:检查环境...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...