文章目录
一、如何在控制器中使用EFCore
1.注册服务
在program.cs文件中添加以下代码。
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("ShirtStoreManagement"));
});
2.获取db对象
在控制器类的构造函数中获取ApplicationDbContext对象,因为已经从注册服务的方法就新建了ApplicationDbContext对象实例。
private readonly ApplicationDbContext db;
public ShirtController(ApplicationDbContext db)
{
this.db = db;
}
3.使用db对象进行crud
使用db对象直接进行数据库交互操作。
[ApiController]
[Route("api/[controller]")]
public class ShirtController : ControllerBase
{
private readonly ApplicationDbContext db;
public ShirtController(ApplicationDbContext db)
{
this.db = db;
}
[HttpGet]
public IActionResult GetShirts()
{
return Ok(db.Shirts.ToList());
}
[HttpGet("{id}")]
[TypeFilter(typeof(Shirt_ValidateShirtIdFilterAttribute))] // 使用TypeFilter目的:执行构造函数,将db传入到对应类中
public IActionResult GetShirtById(int id)
{
return Ok(HttpContext.Items["shirt"]);
}
[HttpPost]
[TypeFilter(typeof(Shirt_ValidateCreateShirtFilterAttribute))]
public IActionResult CreateShirt([FromBody] Shirt shirt)
{
db.Shirts.Add(shirt);
db.SaveChanges();
// 在请求返回的header的location会体现(第一个参数是动作名,第二个是路由参数,第三个是返回数据)
return CreatedAtAction(nameof(GetShirtById), new { id = shirt.ShirtId }, shirt);
}
[HttpPut("{id}")]
[TypeFilter(typeof(Shirt_ValidateShirtIdFilterAttribute))]
[Shirt_ValidateUpdateShirtFilter]
[TypeFilter(typeof(Shirt_HandleUpdateExceptionsFilterAttribute))]
public IActionResult UpdateShirt(int id, Shirt shirt)
{
var shirtToUpdate = HttpContext.Items["shirt"] as Shirt;
shirtToUpdate.Brand = shirt.Brand;
shirtToUpdate.Gender = shirt.Gender;
shirtToUpdate.Color = shirt.Color;
shirtToUpdate.Size = shirt.Size;
shirtToUpdate.Price = shirt.Price;
db.Shirts.Update(shirtToUpdate);
db.SaveChanges();
return NoContent();
}
[HttpDelete("{id}")]
[TypeFilter(typeof(Shirt_ValidateShirtIdFilterAttribute))]
public IActionResult DeleteShirt(int id)
{
var shirtToDelete = HttpContext.Items["shirt"] as Shirt;
db.Shirts.Remove(shirtToDelete);
db.SaveChanges();
return Ok(shirtToDelete);
}
}
二、如何在筛选器中使用EFCore
1.与控制器类中同样操作
注册服务->获取db对象->使用db对象
2.注意事项
获取db对象时,同样时写在筛选器类的构造函数中。使用该筛选器类时,应使用TypeFilter进行特性标注。例如:[TypeFilter(typeof(Shirt_ValidateShirtIdFilterAttribute))]。这样才会执行筛选器类的构造函数,将db传入到对应筛选器类中。
[HttpGet("{id}")]
[TypeFilter(typeof(Shirt_ValidateShirtIdFilterAttribute))] // 使用TypeFilter目的:执行构造函数,将db传入到对应类中
public IActionResult GetShirtById(int id)
{
return Ok(HttpContext.Items["shirt"]);
}
标签:WebAPI,Core,ASP,TypeFilter,shirt,db,id,public,Shirt
From: https://blog.csdn.net/weixin_44458540/article/details/145284720