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() == )
{
// 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
asp.net core 系列之webapi集成EFCore的简单操作教程的更多相关文章
- asp.net core 系列之webapi集成Dapper的简单操作教程
Dapper也是是一种ORM框架 这里记录下,使用ASP.NET 集成 Dapper 的过程,方便自己查看 至于Dapper的特性以及操作可以参考Dapper官方文档 1.创建数据库相关 在Sql S ...
- asp.net core系列 38 WebAPI 返回类型与响应格式--必备
一.返回类型 ASP.NET Core 提供以下 Web API Action方法返回类型选项,以及说明每种返回类型的最佳适用情况: (1) 固定类型 (2) IActionResult (3) Ac ...
- asp.net core 2.0 webapi集成signalr
asp.net core 2.0 webapi集成signalr 在博客园也很多年了,一直未曾分享过什么东西,也没有写过博客,但自己也是汲取着博客园的知识成长的: 这两天想着不能这么无私,最近.N ...
- asp.net core系列 36 WebAPI 搭建详细示例
一.概述 HTTP不仅仅用于提供网页.HTTP也是构建公开服务和数据的API强大平台.HTTP简单灵活且无处不在.几乎任何你能想到的平台都有一个HTTP库,因此HTTP服务可以覆盖广泛的客户端,包括浏 ...
- asp.net core系列 37 WebAPI 使用OpenAPI (swagger)中间件
一.概述 在使用Web API时,对于开发人员来说,了解其各种方法可能是一项挑战.在ASP.NET Core上,Web api 辅助工具介绍二个中间件,包括:Swashbuckle和NSwag .NE ...
- asp.net core系列 77 webapi响应压缩
一.介绍 背景:目前在开发一个爬虫框架,使用了.net core webapi接口作为爬虫调用入口,在调用 webapi时发现爬虫耗时很短(1秒左右),但客户端获取响应时间却在3~4秒.对于这个问题考 ...
- asp.net core系列 61 Ocelot 构建服务发现简单示例
一.概述 Ocelot允许指定服务发现提供程序,如Consul或Eureka. 这二个中间件是用来实现:服务治理或秒服务发现,服务发现查找Ocelot正在转发请求的下游服务的主机和端口.目前Ocelo ...
- asp.net core系列 WebAPI 作者:懒懒的程序员一枚
asp.net core系列 36 WebAPI 搭建详细示例一.概述1.1 创建web项目1.2 添加模型类1.3 添加数据库上下文1.4 注册上下文1.5 添加控制器1.6 添加Get方法1.7 ...
- 【目录】asp.net core系列篇
随笔分类 - asp.net core系列篇 asp.net core系列 68 Filter管道过滤器 摘要: 一.概述 本篇详细了解一下asp.net core filters,filter叫&q ...
随机推荐
- python爬虫入门(六) Scrapy框架之原理介绍
Scrapy框架 Scrapy简介 Scrapy是用纯Python实现一个为了爬取网站数据.提取结构性数据而编写的应用框架,用途非常广泛. 框架的力量,用户只需要定制开发几个模块就可以轻松的实现一个爬 ...
- Linux内核架构与底层--读书笔记
linux中管道符"|"的作用 命令格式:命令A|命令B,即命令1的正确输出作为命令B的操作对象(下图应用别人的图片) 1. 例如: ps aux | grep "tes ...
- 页面读取Excel
var input = document.getElementById("file"); //支持chrome IE10 if (window.FileReader) ...
- 深入理解SpringBoot之装配条件
我们知道自动装配是SpringBoot微服务化的核心,它会把META-INF/spring.factoires里配置的EnableAutoConfiguration注册到IOC容器里.但是,请大家考虑 ...
- Linux时间子系统之(六):POSIX timer
专题文档汇总目录 Notes:首先讲解了POSIX timer的标识(唯一识别).POSIX Timer的组织(管理POSIX Timer).内核中如何抽象POSIX Timer:然后分析了POSIX ...
- 安装nginx和php
安装nginx 1.安装依赖包 yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel perl pe ...
- 论文阅读 | CrystalBall: A Visual Analytic System for Future Event Discovery and Analysis from Social Media Data
CrystalBall: A Visual Analytic System for Future Event Discovery and Analysis from Social Media Data ...
- Spring Boot + Websocket + Thymeleaf + Lombok
https://github.com/guillermoherrero/websocket 验证错误消息文件名字:是默认名ValidationMessages.properties,编译后存放在cla ...
- Spring的两种任务调度Scheduled和Async
Spring提供了两种后台任务的方法,分别是: 调度任务,@Schedule 异步任务,@Async 当然,使用这两个是有条件的,需要在spring应用的上下文中声明<task:annotati ...
- Ajax 与服务器通信 验证编号重复
在最近的一个Web项目中,需要实现一个功能,就是用户在前端输入一个编号,后台需要验证这个编号是否在数据库中已经存在,如果存在就提示用户. 主要用到两个模块.第一:在jsp中添加一个脚本,利用ajax向 ...