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 ...
随机推荐
- Page.ClientScript.RegisterStartupScript用法小结
使用类型.键.脚本文本和指示是否添加脚本标记的布尔值向 Page 对象注册启动脚本. 参数 type 要注册的启动脚本的类型. key 要注册的启动脚本的键. script 要注册的启动脚本文本. a ...
- JavaScript和JQuery的区别
一.本质上的区别 1.JavaScript 是通过<script></script>标签插入到HTML页面,可由所有的现代浏览器执行的一种轻量级的编程语言. 2.JQuery是 ...
- Coding theano under remote ubuntu server from local Mac (在本地mac机器上,写、跑、调试、看-远程ubuntu上的theano代码)
本人是奇葩,最近鼓捣了一套在mac上coding远程ubuntu上的theano代码的东东,记之以期造福后人. Overview: 下图是我的编程环境和网络环境 我期望能在本地mac机器上对远程的ub ...
- macbook 添加快捷启动服务
来至 Mac OS X: Launch Terminal from keyboard shortcut os x 上很多功能都可以通过Apple自家的Automator.app创建,且使用此方法可以为 ...
- 言简意赅的TIME_WAIT
为什么要有TIME_WAIT? 主动关闭端发送完ACK后等2MSL(最长分节生命期),防止对端没有收到ACK这种情况,重发. 官方点,再官方点...... (1) 可靠地实现TCP全双工连接的终止: ...
- activemq的消息确认机制ACK
一.简介 消息消费者有没有接收到消息,需要有一种机制让消息提供者知道,这个机制就是消息确认机制. ACK(Acknowledgement)即确认字符,在数据通信中,接收站发给发送站的一种传输类控制字符 ...
- springboot中自定义根路径的配置
Spring boot默认是/ ,这样直接通过http://ip:port/就可以访问到index页面,如果要修改为http://ip:port/path/ 访问的话,那么需要在Application ...
- 用nginx缓存静态文件
这篇教程说明你应该怎样配置 nginx.设置 HTTP 头部过期时间,用 Cache-Control 中的 max-age 标记为静态文件(比如图片. CSS 和 Javascript 文件) ...
- 手把手教你创建「人物角色Persona」
一.为什么要创建人物角色 下图来自 Cooper interaction design ,同样有购车需求的用户,用车的人不同.各自的目的不同,最终满足需求的车型也有很大差异.对于汽车公司而言,在车辆设 ...
- Embedded servlet containers
73. Embedded servlet containers 73.1 Add a Servlet, Filter or Listener to an application There are t ...