Controller Base CRUD method examples in minimal .net 7.0 web api

164 views Asked by At

I cannot find the correct syntax for retrieving one model entity via the context e.g. Yes I know that I should probably be using the extension lambda methods in Program.cs, but I see no reason why we cannot 'mix and match' here! I'm building a restful API and don't need or want views, so I only need ControllerBase. But I'd still like to structure my project with Controller methods and classes neatly!

namespace AdventureWorks2017API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SalesOrderController : ControllerBase
    {
        private readonly AdventureWorks2017Context _context;

        public SalesOrderController(AdventureWorks2017Context context)
        {
            _context = context;
        }

        [HttpGet("GetAllSales")]
        public List<SalesOrderDetail> GetAllSales()
        {
            return _context.SalesOrderDetails.ToList();
        }

        [HttpGet("GetSale")]
        public SalesOrderDetail GetSale(int id)
        {         
            return _context.SalesOrderDetails.Find(id);          
        }
    }
}

I get a possible null reference warning in the getsale (by id) method.

This is the link I used, but the author doesn’t elaborate on crud or LINQ!!

https://geeksarray.com/blog/getting-started-with-aspnet-core-web-api-and-entity-framework

1

There are 1 answers

0
Paul Kersey On

So I've figured it out. Firstly, I should check for null, then to do things properly either return a 404 not found, or 200 OK response.

If we want to add some validations into the action and return a validation failure with a 400 Bad Request response, you can't return a specific type or custom entity and we have to use either IActionResult or ActionResult types.

Now I just need to work out the insert, update and delete methods. Then I will follow this excellent link: https://danielk.tech/home/net-core-api-server-how-to-create-a-base-crud-controller

[HttpGet("GetSale/{SalesOrderDetailID}")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public ActionResult<SalesOrderDetail> GetSale(int id)
    {
        var result = _context.SalesOrderDetails.Find(id);

        if (result == null) { return NotFound(); }
        else
        {
            return Ok(result);
        }
        
    }