.NET 6 Entity Framework Core Db First(2) 增删改查
基础代码
- 在Program.cs注入DemoContext
- 新建HomeController,继承ControllerBase
- 添加Controller特性,[ApiController] [Route("[controller]/{action=index}")]
- 通过构造函数获取数据库上下文实例(DemoContext)
接口地址
为了方便测试,这里全部使用了HttpGet,也不需要传参数
1、查询
- http://localhost:5109/home
- http://localhost:5109/home/get/2
2、添加
- http://localhost:5109/home/add
3、修改
- http://localhost:5109/home/edit
4、删除
- http://localhost:5109/home/delete
具体代码
Program.cs
using EFDBFirstDemo.Model.Context; using Microsoft.EntityFrameworkCore; var builder = WebApplication.CreateBuilder(args); // Add services to the container. var connectionString = builder.Configuration.GetConnectionString("demo"); builder.Services.AddDbContext<DemoContext>(options => options.UseSqlServer(connectionString)); //数据库异常筛选器 builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddControllers(); var app = builder.Build(); // Configure the HTTP request pipeline. app.UseAuthorization(); app.MapControllers(); app.Run();
HomeController.cs
namespace EFDBFirstDemo.API.Controllers { [ApiController] [Route("[controller]/{action=index}")] public class HomeController : ControllerBase { public DemoContext _demoContext; public HomeController(DemoContext demoContext) { _demoContext = demoContext; } public IActionResult Index() { var result = _demoContext.Students.ToList(); return Ok(result); } [Route("{id?}")] public async Task<IActionResult> Get(int id) { var result = await _demoContext.Students.FindAsync(id); //var result = _demoContext.Students.FirstOrDefault(l => l.Id == id); return Ok(result); } //[HttpPost] public async Task<IActionResult> Add() { var student = new Student { StudentName = "张三", EnrollmentData = DateTime.Now }; _demoContext.Add(student); var result = await _demoContext.SaveChangesAsync(); return Ok(result); } //[HttpPost] public async Task<IActionResult> Edit() { var student = new Student { Id = 2, StudentName = "李四", EnrollmentData = DateTime.Now }; _demoContext.Update(student); var result = await _demoContext.SaveChangesAsync(); return Ok(result); } //[HttpPost] public async Task<IActionResult> Delete() { var student = new Student { Id = 1 }; //_demoContext.Students.Remove(student); _demoContext.Remove(student); var result = await _demoContext.SaveChangesAsync(); return Ok(result); } } }