ASP.NET Core Web API 示範 - CRUD Database First,GET,POST,PUT,DELETE

ASP.NET Core Web API 入門教學

影片講解


需要安裝以下套件 
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();
    }
}

 

範例檔:下載

參考資料: 
教學課程:使用 ASP.NET Core 建立 Web API




Copyright © 凱哥寫程式 2022 | Powered by TalllKai ❤