因为官网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的简单操作教程的更多相关文章

  1. asp.net core 系列之webapi集成Dapper的简单操作教程

    Dapper也是是一种ORM框架 这里记录下,使用ASP.NET 集成 Dapper 的过程,方便自己查看 至于Dapper的特性以及操作可以参考Dapper官方文档 1.创建数据库相关 在Sql S ...

  2. asp.net core系列 38 WebAPI 返回类型与响应格式--必备

    一.返回类型 ASP.NET Core 提供以下 Web API Action方法返回类型选项,以及说明每种返回类型的最佳适用情况: (1) 固定类型 (2) IActionResult (3) Ac ...

  3. asp.net core 2.0 webapi集成signalr

    asp.net core 2.0 webapi集成signalr   在博客园也很多年了,一直未曾分享过什么东西,也没有写过博客,但自己也是汲取着博客园的知识成长的: 这两天想着不能这么无私,最近.N ...

  4. asp.net core系列 36 WebAPI 搭建详细示例

    一.概述 HTTP不仅仅用于提供网页.HTTP也是构建公开服务和数据的API强大平台.HTTP简单灵活且无处不在.几乎任何你能想到的平台都有一个HTTP库,因此HTTP服务可以覆盖广泛的客户端,包括浏 ...

  5. asp.net core系列 37 WebAPI 使用OpenAPI (swagger)中间件

    一.概述 在使用Web API时,对于开发人员来说,了解其各种方法可能是一项挑战.在ASP.NET Core上,Web api 辅助工具介绍二个中间件,包括:Swashbuckle和NSwag .NE ...

  6. asp.net core系列 77 webapi响应压缩

    一.介绍 背景:目前在开发一个爬虫框架,使用了.net core webapi接口作为爬虫调用入口,在调用 webapi时发现爬虫耗时很短(1秒左右),但客户端获取响应时间却在3~4秒.对于这个问题考 ...

  7. asp.net core系列 61 Ocelot 构建服务发现简单示例

    一.概述 Ocelot允许指定服务发现提供程序,如Consul或Eureka. 这二个中间件是用来实现:服务治理或秒服务发现,服务发现查找Ocelot正在转发请求的下游服务的主机和端口.目前Ocelo ...

  8. 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 ...

  9. 【目录】asp.net core系列篇

    随笔分类 - asp.net core系列篇 asp.net core系列 68 Filter管道过滤器 摘要: 一.概述 本篇详细了解一下asp.net core filters,filter叫&q ...

随机推荐

  1. ORACLE 数据库选择性导出表中数据&导入已存在表数据

    在dos界面下选择性导出表中的数据语句为: exp his/linker@orcl tables=(sysreprot) file="D:\20131218.dmp" query= ...

  2. Linux 下 Redis 安装与配置

    1.Redis 的安装 在 Ubuntu 系统安装 redis 可以使用以下命令: $ sudo apt-get update $ sudo apt-get install redis-server ...

  3. DataFrame

    DataFrame是一个表格型的数据结构,含有一组有序的列,每列可以是不同的值类型(数值.字符串.布尔值等),DataFrame就行索引也有列索引,可以被看做由Series组成的字典(共用同一个索引) ...

  4. Mysql连接问题:com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException

    com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establish ...

  5. PAT1099:Build A Binary Search Tree

    1099. Build A Binary Search Tree (30) 时间限制 100 ms 内存限制 65536 kB 代码长度限制 16000 B 判题程序 Standard 作者 CHEN ...

  6. @EnableTransactionManagement注解理解

    @EnableTransactionManagement表示开启事务支持,在springboot项目中一般配置在启动类上,效果等同于xml配置的<tx:annotation-driven /&g ...

  7. SSM-SpringMVC-05:SpringMVC视图解析器InternalResourceViewResolver配置

     ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 视图解析器------默认就有配置,但是默认的在实际使用过程中有很多不方便的地方,所以我们配置一道视图解析器 ...

  8. 查找linux设备的uuid

    [root@ ~]# blkid /dev/vdc /dev/vdc: UUID="bxxxx-xxx-41b9-8146-7da8bd645b92" TYPE="ext ...

  9. Linux上配置使用iSCSI详细说明

    本文详细介绍iSCSI相关的内容,以及在Linux上如何实现iSCSI. 第1章 iSCSI简介 1.1 scsi和iscsi 传统的SCSI技术是存储设备最基本的标准协议,但通常需要设备互相靠近并用 ...

  10. TestNG详解-深度好文

    转自: https://blog.csdn.net/lykangjia/article/details/56485295 TestNG详解-深度好文 2017年02月22日 14:51:52 阅读数: ...