asp.net core 系列之webapi集成EFCore的简单操作教程
?
因為官網asp.net core webapi教程部分,給出的是使用內存中的數據即 UseInMemoryDatabase 的方式,
這里記錄一下,使用SQL Server數據庫的方式即 UseSqlServer 的方式。
?
環境說明:
這里使用的是win 7 下的 virtual studio 2017 ,數據庫使用的Sql Server
?
1.創建一個web項目
- 文件->新建->項目
- 選擇 ASP.NET Core Web 應用 的模板,項目名 WebApiDemo
- 在新的 ASP.NET Core Web 應用的頁面,選擇 API 模板,并確定,不要選擇支持Docker
?
?
?
?
2.增加一個實體類
- 右擊項目,新增一個Models文件夾
- 在Models文件夾下增加一個類(class),TodoItem
代碼如下
public class TodoItem{public long Id { get; set; }public string Name { get; set; }public bool IsComplete { get; set; }}?
3.增加一個數據庫上下文實體(database context)
- 右鍵Models文件夾,增加一個類,命名?TodoContext
代碼如下
public class TodoContext : DbContext{public TodoContext(DbContextOptions<TodoContext> options): base(options){}public DbSet<TodoItem> TodoItems { get; set; }}?
4.注冊數據庫上下文實體
在 ASP.NET Core 中 ,服務(service)例如 數據庫上下文(the DB context),必須被注冊到 DI 容器中;
容器可以給Controller 提供 服務 (service).
?
StartUp.cs代碼如下
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();}}?
注意,這里是不同于官網教程中的地方,對比如下
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"} }
?
5.增加初始化遷移,更新數據庫
此步驟,主要是使用code first 方式,在數據庫中,創建相應的數據庫和實體對應的表
對應?appsettings.json 文件中的連接字符串 :數據庫名 WebApiDemo
- 工具-> NuGet 包管理器 -> 程序包管理器控制臺
?
控制臺如下:
?
命令如下:
Add-Migration Initial Update-Database?
注意,這里要求 power shell 版本 需要是3.0及以上,如果版本不夠,可以自己百度然后升級power shell,這里不再詳述
?
6.增加 Controller 控制器
- 右鍵 Controllers 文件夾
- 添加->控制器
- 選擇 空 API 控制器,命名 TodoController ,添加
?
代碼如下:
[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項目
?
7.運行,輸入瀏覽器地址檢驗
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
??
轉載于:https://www.cnblogs.com/Vincent-yuan/p/10777664.html
總結
以上是生活随笔為你收集整理的asp.net core 系列之webapi集成EFCore的简单操作教程的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Easy Scheduler 1.0.2
- 下一篇: JS异步操作新体验之 async函数