.Net Core Web Api连接MongoDB自动创建表格并实现CRUD功能
以下是一个使用ASP.NET Core Web API连接MongoDB,并实现创建(Create)、读取(Read)、更新(Update)和删除(Delete)功能的简化示例。
首先,确保你已经安装了MongoDB,并在项目中安装了MongoDB.Driver。
// 使用MongoDB.Driver连接MongoDB并创建MongoClient实例
using MongoDB.Driver;
public class MongoDbService
{
private readonly IMongoCollection<YourEntity> _collection;
public MongoDbService(string connectionString, string databaseName, string collectionName)
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase(databaseName);
_collection = database.GetCollection<YourEntity>(collectionName);
}
// 创建记录
public async Task CreateAsync(YourEntity entity)
{
await _collection.InsertOneAsync(entity);
}
// 读取记录
public async Task<List<YourEntity>> ReadAsync()
{
return await _collection.Find(entity => true).ToListAsync();
}
// 更新记录
public async Task UpdateAsync(string id, YourEntity entity)
{
await _collection.ReplaceOneAsync(e => e.Id == id, entity);
}
// 删除记录
public async Task DeleteAsync(string id)
{
await _collection.DeleteOneAsync(e => e.Id == id);
}
}
// 实体类YourEntity,应该包含Id属性
public class YourEntity
{
[BsonId]
public string Id { get; set; }
// 其他属性...
}
在你的Startup.cs中配置服务:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<MongoDbService>();
}
在你的Controller中使用MongoDbService:
[ApiController]
[Route("[controller]")]
public class YourController : ControllerBase
{
private readonly MongoDbService _mongoDbService;
public YourController(MongoDbService mongoDbService)
{
_mongoDbService = mongoDbService;
}
[HttpPost]
public async Task<IActionResult> Create(YourEntity entity)
{
await _mongoDbService.CreateAsync(entity);
return Ok(entity);
}
[HttpGet]
public async Task<IActionResult> Read()
{
var entities = await _mongoDbService.ReadAsync();
return Ok(entities);
}
[HttpPut("{id}")]
public async Task<IActionResult> Update(string id, YourEntity entity)
{
await _mongoDbService.UpdateAsync(id, entity);
return Ok(entity);
}
[HttpDelete("{id}")]
public async Task<IAction
评论已关闭