手把手教你ASP.NET Core:使用Entity Framework Core进行增删改查
新建表Todo,如图

添加模型类
在“解决方案资源管理器”中,右键单击项目。 选择“添加” > “新建文件夹”。 将文件夹命名为 Models。
右键单击 Models 文件夹,然后选择“添加” > “类” 。 将类命名为 Todo,然后选择“添加”。
using System;
namespace Course001.Models
{
public class Todo
{
public Guid Id { get; set; }
public string Name { get; set; }
}
}
添加数据库上下文
右键单击 Models 文件夹,然后选择“添加” > “类” 。 将类命名为 TodoContext,然后单击“添加”。
using Microsoft.EntityFrameworkCore;
namespace Course001.Models
{
public class TodoContext : DbContext
{
public TodoContext(DbContextOptions options)
: base(options)
{
}
public DbSet Todos { get; set; }
}
}
注册数据库上下文
在 ASP.NET Core 中,服务(如数据库上下文)必须向依赖关系注入 (DI) 容器进行注册。 该容器向控制器提供服务。
在Startup.cs文件中增加services.AddDbContext,代码如下:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<TodoContext>(opt =>opt.UseSqlServer(Configuration.GetConnectionString("TodoContext")));
services.AddControllers();
}
在appsettings.json文件中增加ConnectionStrings,代码如下:
"ConnectionStrings": {
"TodoContext": "server=.\\SQLEXPRESS;database=Course;uid=sa;pwd=123456;Pooling='true';Min Pool Size=3;"
},
修改TodosController.cs文件实现增删改查
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Course001.Models;
namespace Course001.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TodosController : ControllerBase
{
private readonly TodoContext context;
public TodosController(TodoContext context)
{
this.context = context;
}
/// <summary>
/// 获取所有待办事项
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<ActionResult<IEnumerable<Todo>>> GetTodos()
{
return await context.Todo.ToListAsync();
}
/// <summary>
/// 按ID获取项
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpGet("{id}")]
public async Task<ActionResult<Todo>> GetTodo(Guid id)
{
var todo = await context.Todo.FindAsync(id);
if (todo == null)
{
return NotFound();
}
return todo;
}
/// <summary>
/// 添加新项
/// </summary>
/// <param name="todo"></param>
/// <returns></returns>
[HttpPost]
public async Task<ActionResult<Todo>> PostTodo(Todo todo)
{
todo.Id = Guid.NewGuid();
context.Todo.Add(todo);
await context.SaveChangesAsync();
return CreatedAtAction("GetTodo", new { id = todo.Id }, todo);
}
/// <summary>
/// 更新现有项
/// </summary>
/// <param name="id"></param>
/// <param name="todo"></param>
/// <returns></returns>
[HttpPut("{id}")]
public async Task<ActionResult<Todo>> PutTodo(Guid id, Todo todo)
{
var oldTodo = await context.Todo.FindAsync(id);
oldTodo.Name = todo.Name;
context.Entry(oldTodo).State = EntityState.Modified;
await context.SaveChangesAsync();
return oldTodo;
}
/// <summary>
/// 删除项
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<ActionResult<Todo>> DeleteTodo(Guid id)
{
var todo = await context.Todo.FindAsync(id);
if (todo == null)
{
return NotFound();
}
context.Todo.Remove(todo);
await context.SaveChangesAsync();
return todo;
}
}
}
通过 Postman 测试 添加新项
创建新请求。
将 HTTP 方法设置为“POST”。
将请求 URI 设置为 https://localhost:44342/api/todos。
选择“正文”选项卡。
选择“原始”单选按钮。
将类型设置为 JSON (application/json)
在请求正文中,输入待办事项的 JSON:
{
"Name":"遛狗"
}选择Send。

小结
到此我们的 ASP.NET Core API项目,已经实现“待办事项”的增删改查。但这些仅仅作为Demo参考,接下来我们会深入介绍一下我们在ASP.NET Core应用到的这些技术。
手把手教你ASP.NET Core:使用Entity Framework Core进行增删改查的更多相关文章
- entity framework 新手入门篇(2)-entity framework基本的增删改查
经过前两节的简单描述,终于可以进入entity framework的使用部分了.本节将对entity framework原生的增删改查进行讲解. 承接上面的部分,我们有一个叫做House的数据库,其中 ...
- Entity Framework学习 - 2.增删改查
1.增加数据 PirateBayEntities db = new PirateBayEntities(); T_Tests test = new T_Tests(); test.Name = &qu ...
- ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Fram ...
- Entity Framework公共的增删改方法
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.I ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 更新关系数据
Updating related data¶ 7 of 7 people found this helpful The Contoso University sample web applicatio ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 创建复杂数据模型
Creating a complex data model 创建复杂数据模型 8 of 9 people found this helpful The Contoso University sampl ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 读取关系数据
Reading related data¶ 9 of 9 people found this helpful The Contoso University sample web application ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio »迁移
Migrations¶ 4 of 4 people found this helpful The Contoso University sample web application demonstra ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 排序、筛选、分页以及分组
Sorting, filtering, paging, and grouping 7 of 8 people found this helpful By Tom Dykstra The Contoso ...
- Working with Data » Getting started with ASP.NET Core and Entity Framework Core using Visual Studio » 增、查、改、删操作
Create, Read, Update, and Delete operations¶ 5 of 5 people found this helpful By Tom Dykstra The Con ...
随机推荐
- 详解 `HTTP` 系列之一
前言 本文介绍的是HTTP的基础知识,包括HTTP的由来.HTTP的报文信息.状态码.HTTP三个版本的对比等.希望这篇简短的文章能对大家认识HTTP协议提供帮助. HTTP的前世今生 HTTP 由来 ...
- 为什么网站URL需要设置为静态化
http://www.wocaoseo.com/thread-95-1-1.html 为什么网站URL需要静态化?网站url静态化的好处是什么?现在很多网站的链接都是静态规的链接,但是网站 ...
- SwiftUI - Grid View 的实现方法,逐步剖析助你实现
简介 在当前正式 SwiftUI 版本而言,很多控件都是缺少的.比如在 UIKit 框架里有 UICollectionView 组件,可以很方便地做 Gird 格子类型的视图.但是在 SwiftUI ...
- 同事跳槽阿里P7,甩我一份微服务架构设计模式文档,看完我也去
给所有微服务架构开发者的忠告,我想对你们说: 第一,要记住微服务不是解决所有问题的万能“银弹”. 第二,编写整洁的代码和使用自动化测试至关重要,因为这是现代软件开发的基础. 第三,关注微服务的本质,即 ...
- .net core学习笔记,组件篇:服务的注册与发现(Consul)初篇
1.什么是服务注册中心? 在学习服务注册与发现时,我们要先搞明白到底什么是服务注册与发现. 在这里我举一个生活中非常普遍的例子——网购来简单说明,网购在我们日常生活中已经是非常普遍了,其实网购中的(商 ...
- windows下安装jdk+tomcat+maven并配置
一.下载安装jdk并配置 1.1 进行JDK下载 下载地址:一键直达 一般下载后,安装位置默认,一路下一步,一直到安装完毕-"关闭". 1.2 环境变量配置 不要管是不是一般情况, ...
- Fitness - 05.04
倒计时241天 运动38分钟,共计9组.拉伸10分钟. 每组跑步2分钟(6.3KM/h),走路2分钟(6KM/h). 上午下了课,直奔健身房. 手机坏了,没有听音乐. 没有吃午饭,但是上午喝的咖啡还是 ...
- 在Fragment 中拦截返回键
代码如下: class XXXFrgmt : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ...
- java-对象引用和对象本身
示意图 应用场景 1.赋值 只有用新的对象本身直接赋值给对应引用,该对象引用的值会改变,因为对象引用指向的对象本身改变了. 2.方法入参 调用方法和被调用方法. 代码 import com.aliba ...
- robotframework自动化测试框架搭建及问题汇总
1.安装python RF框架是基于python 的,所以一定要有python环境,python与rf存在兼容性问题,我安装的是python3.7.5,robotframework3.1.2. 选择添 ...