ASP.NET Core .NET 5 打造WebAPI入門教學(SP_1) - CRUD Database First,GET,POST,PUT,DELETE

Leave a Comment

需要安裝以下套件
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

指令
Scaffold-DbContext "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Todo.mdf;Integrated Security=True;Connect Timeout=30" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Force -CoNtext TodoContext

appsettings.json
{
  "ConnectionStrings": {
    "TodoDatabase": "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=D:\\Todo.mdf;Integrated Security=True;Connect Timeout=30"
}, }

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TodoDatabase"))); }

程式碼
    [Route("api/[controller]")]
    [ApiController]
    public class TodoItemsController : ControllerBase
    {
        private readonly TodoContext _context;

        public TodoItemsController(TodoContext context)
        {
            _context = context;
        }

        [HttpGet]
        public ActionResult<IEnumerable<TodoItem>> Get()
        {
            return _context.TodoItems;
        }

        [HttpGet("{id}")]
        public ActionResult<TodoItem> GetTodoItem(Guid id)
        {
            var result = _context.TodoItems.Find(id);
            if (result == null)
            {
                return NotFound("沒有資料");
            }
            return result;
        }

        [HttpPost]
        public ActionResult<TodoItem> Post([FromBody] TodoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            _context.SaveChanges();

            return CreatedAtAction(nameof(Put), new { id = todoItem.Id }, todoItem);
        }

        [HttpPut("{id}")]
        public IActionResult Put(Guid id, [FromBody] TodoItem todoItem)
        {
            if (id != todoItem.Id)
            {
                return BadRequest();
            }

            _context.Entry(todoItem).State = EntityState.Modified;

            try
            {
                _context.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_context.TodoItems.Any(e => e.Id == id))
                {
                    return NotFound();
                }
                else
                {
                    return StatusCode(500, "存取發生錯誤");
                }
            }
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult Delete(Guid id)
        {
            var result =  _context.TodoItems.Find(id);

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

            _context.TodoItems.Remove(result);
             _context.SaveChanges();

            return NoContent();
        }
    }

範例下載:下載

0 意見:

張貼留言

技術提供:Blogger.