由於官網asp.net core webapi教程部分,給出的是使用內存中的數據即 UseInMemoryDatabase 的方式,ios
這裏記錄一下,使用SQL Server數據庫的方式即 UseSqlServer 的方式。web
環境說明:sql
這裏使用的是win 7 下的 virtual studio 2017 ,數據庫使用的Sql Servershell
代碼以下數據庫
public class TodoItem { public long Id { get; set; } public string Name { get; set; } public bool IsComplete { get; set; } }
代碼以下json
public class TodoContext : DbContext { public TodoContext(DbContextOptions<TodoContext> options) : base(options) { } public DbSet<TodoItem> TodoItems { get; set; } }
在 ASP.NET Core 中 ,服務(service)例如 數據庫上下文(the DB context),必須被註冊到 DI 容器中;api
容器能夠給Controller 提供 服務 (service).瀏覽器
StartUp.cs代碼以下app
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<TodoContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DemoContext"))); //使用SqlServer數據庫 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); } }
注意,這裏是不一樣於官網教程中的地方,對好比下asp.net
ConfigureService方法中:
//官網
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
//本教程 services.AddDbContext<TodoContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DemoContext")));
Configuration.GetConnectionString("DemoContext") 取得是 appsettings.json 文件中的 字符串,以下
appsettings.json 內容:
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "TodoContext": "Server=(localdb)\\mssqllocaldb;Database=WebApiDemo;Trusted_Connection=True;MultipleActiveResultSets=true" } }
此步驟,主要是使用code first 方式,在數據庫中,建立相應的數據庫和實體對應的表
對應 appsettings.json 文件中的鏈接字符串 :數據庫名 WebApiDemo
控制檯以下:
命令以下:
Add-Migration Initial
Update-Database
注意,這裏要求 power shell 版本 須要是3.0及以上,若是版本不夠,能夠本身百度而後升級power shell,這裏再也不詳述
代碼以下:
[Route("api/[controller]")] [ApiController] public class TodoController : ControllerBase { private readonly TodoContext _context; public TodoController(TodoContext context) { _context = context; if (_context.TodoItems.Count() == 0) { // Create a new TodoItem if collection is empty, // which means you can't delete all TodoItems. _context.TodoItems.Add(new TodoItem { Name = "Item1" }); _context.SaveChanges(); } } // GET: api/Todo [HttpGet] public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems() { return await _context.TodoItems.ToListAsync(); } // GET: api/Todo/5 [HttpGet("{id}")] public async Task<ActionResult<TodoItem>> GetTodoItem(long id) { var todoItem = await _context.TodoItems.FindAsync(id); if (todoItem == null) { return NotFound(); } return todoItem; } }
這裏面有兩個方法,主要是爲了檢驗是否成功建立此webapi項目
https://localhost:44385/api/todo
這裏用戶根據本身的地址替換便可
這裏做簡單記錄,方便本身往後查看,若有錯誤,歡迎指正
參考網址:
https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio
https://docs.microsoft.com/en-us/aspnet/core/tutorials/razor-pages/model?view=aspnetcore-2.2&tabs=visual-studio