新建表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进行增删改查的更多相关文章

  1. entity framework 新手入门篇(2)-entity framework基本的增删改查

    经过前两节的简单描述,终于可以进入entity framework的使用部分了.本节将对entity framework原生的增删改查进行讲解. 承接上面的部分,我们有一个叫做House的数据库,其中 ...

  2. Entity Framework学习 - 2.增删改查

    1.增加数据 PirateBayEntities db = new PirateBayEntities(); T_Tests test = new T_Tests(); test.Name = &qu ...

  3. ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程

    原文:ASP.NET Core 配置 Entity Framework Core - ASP.NET Core 基础教程 - 简单教程,简单编程 ASP.NET Core 配置 Entity Fram ...

  4. Entity Framework公共的增删改方法

    using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.I ...

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

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

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

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

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

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

随机推荐

  1. Entity Framework 6 实体某些字段根据模型状态进行自动更新内容

    1.定义基础实体对象 public class BaseEntity { public int Id { get; set; } public DateTime? CreateTime { get; ...

  2. 使用intellij IDEA远程连接服务器部署项目

    由于不想每次打开上传的文件软件,故研究使用intellij IDEA集成 ,下面是我使用的过程的一些记录. 使用intellij 远程连接服务器连接Linux服务器部署项目,方便我们开发测试. 本人使 ...

  3. laravel中elastisearch安装和测试运行是否成功(注意是windows下的操作)

    1.去elasticsearch官网下载,如果太慢可以在我上一个随笔看下载地址 2.下载完解压缩,在cmd中找到到elasticsearch的bin目录下执行.\elasticsearch.bat - ...

  4. android开发之集成zxing,二维码,以及扫描二维码的功能实现。带源代码下载

    package cc.jiusansec.www; import com.google.zxing.WriterException; import com.zxing.activity.Capture ...

  5. 攻防世界——Misc新手练习区解题总结<2>(5-8题)

    第五题gif: 下载附件后,解压得到这样一个文件 几经寻找无果后,发现是不是可以将gif中的黑白图片看做二进制的数字,进而进行解密 最后用二进制转文本得到flag 第六题掀桌子: 看起来是16进制的密 ...

  6. 在C++/CLI环境下,千万不要把普通全局函数当标准C/C++的函数指针传递给native的库使用

    先上一个简单代码: #include <cstdlib> #include <cstdio> // native apis extern "C" { typ ...

  7. 当年偶然发现的 Java Bug(JDK 9及之前仍未修复)

    背景 15年在中信银行做持续集成时,由于当时的项目是基于三方采购的 Java 配置开发平台做的,平台自己基于 Ant 插件实现了增量和热部署. 其中有几个项目在持续集成部署时,经常发现 Linux 平 ...

  8. 【Gin-API系列】部署和监控(九)

    本文是[Gin-API系列]的最后一篇文章,简单介绍如何在生产环境的部署架构和监控手段. 生产部署 部署架构 使用Nginx加Keepalived的方式搭建,可以达到高可用的效果,并可以横向扩容 如何 ...

  9. 20190923-08Linux压缩和解压类 000 016

    gzip/gunzip 压缩 1.基本语法 gzip 文件 (功能描述:压缩文件,只能将文件压缩为*.gz文件) gunzip 文件.gz (功能描述:解压缩文件命令) 2.经验技巧 (1)只能压缩文 ...

  10. 20190919-02安装Xshell和CRT远程工具 000 008

    Linux远程登录及相关工具介绍 Linux一般作为服务器使用,而服务器一般放在机房,你不可能在机房操作你的Linux服务器.这时我们就需要远程登录到Linux服务器来管理维护系统. Linux系统中 ...