CREATE TABLE [dbo].[Todo]( [Id] [uniqueidentifier] NOT NULL, [Name] [nvarchar](100) NULL, CONSTRAINT [PK_Todo] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO
using System; namespace App001.Models { public class Todo { public Guid Id { get; set; } public string Name { get; set; } } }
using Microsoft.EntityFrameworkCore; namespace App001.Models { public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } public DbSet<Todo> Todos { get; set; } } }
在 ASP.NET Core 中,服務(如數據庫上下文)必須向依賴關係注入 (DI) 容器進行註冊。 該容器向控制器提供服務。數據庫
在Startup.cs文件中增長services.AddDbContext,代碼以下:json
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt =>opt.UseSqlServer(Configuration.GetConnectionString("TodoContext"))); services.AddControllers(); }
在appsettings.json文件中增長ConnectionStrings,代碼以下:api
"ConnectionStrings": { "TodoContext": "server=.\\SQLEXPRESS;database=App001;uid=sa;pwd=123456;Pooling='true';Min Pool Size=3;" },
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using App001.Models; namespace App001.Controllers { [Route("api/[controller]")] [ApiController] public class TodosController : ControllerBase { private readonly TodoContext context; public TodosController(TodoContext context) { this.context = context; } /// <summary> /// 獲取全部待辦事項 /// </summary> /// <returns></returns> [HttpGet] public async Task<ActionResult<IEnumerable<Todo>>> GetTodos() { return await context.Todo.ToListAsync(); } /// <summary> /// 按ID獲取項 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] public async Task<ActionResult<Todo>> GetTodo(Guid id) { var todo = await context.Todo.FindAsync(id); if (todo == null) { return NotFound(); } return todo; } /// <summary> /// 添加新項 /// </summary> /// <param name="todo"></param> /// <returns></returns> [HttpPost] public async Task<ActionResult<Todo>> PostTodo(Todo todo) { todo.Id = Guid.NewGuid(); context.Todo.Add(todo); await context.SaveChangesAsync(); return CreatedAtAction("GetTodo", new { id = todo.Id }, todo); } /// <summary> /// 更新現有項 /// </summary> /// <param name="id"></param> /// <param name="todo"></param> /// <returns></returns> [HttpPut("{id}")] public async Task<ActionResult<Todo>> PutTodo(Guid id, Todo todo) { var oldTodo = await context.Todo.FindAsync(id); oldTodo.Name = todo.Name; context.Entry(oldTodo).State = EntityState.Modified; await context.SaveChangesAsync(); return oldTodo; } /// <summary> /// 刪除項 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id}")] public async Task<ActionResult<Todo>> DeleteTodo(Guid id) { var todo = await context.Todo.FindAsync(id); if (todo == null) { return NotFound(); } context.Todo.Remove(todo); await context.SaveChangesAsync(); return todo; } } }
{ "Name":"遛狗" }