asp.net core 6.0 efcore +sqlserver增删改查的demo

news/2024/5/19 21:08:23 标签: .netcore, efcore

efcore_sqlserverdemo_0">asp.net core 6.0 efcore +sqlserver增删改查的demo

下面是一个使用ASP.NET Core 5.0和Entity Framework Core进行增删改查操作的示例。

首先,创建一个空的ASP.NET Core 6.0 Web应用程序项目。

然后,安装以下NuGet包:

Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
接下来,创建一个数据库上下文类,用于定义实体类和数据库连接配置。在项目中创建一个名为AppDbContext.cs的文件,并添加以下代码:

using Microsoft.EntityFrameworkCore;

namespace EFCoreDemo.Models
{
    public class AppDbContext : DbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
        {
        }

        public DbSet<Customer> Customers { get; set; }
    }
}

然后,创建一个实体类来表示数据库表。在项目中创建一个名为Customer.cs的文件,并添加以下代码:

namespace EFCoreDemo.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

接下来,配置数据库连接。打开appsettings.json文件,并添加以下内容:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=EFCoreDemo;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

然后,在Startup.cs文件的ConfigureServices方法中添加以下代码,用于配置数据库上下文的依赖注入:

services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

接下来,创建一个控制器类来处理增删改查操作。在项目中创建一个名为CustomersController.cs的文件,并添加以下代码:

using EFCoreDemo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace EFCoreDemo.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class CustomersController : ControllerBase
    {
        private readonly AppDbContext _dbContext;

        public CustomersController(AppDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Customer>>> GetCustomers()
        {
            return await _dbContext.Customers.ToListAsync();
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> GetCustomer(int id)
        {
            var customer = await _dbContext.Customers.FindAsync(id);

            if (customer == null)
            {
                return NotFound();
            }

            return customer;
        }

        [HttpPost]
        public async Task<ActionResult<Customer>> CreateCustomer(Customer customer)
        {
            _dbContext.Customers.Add(customer);
            await _dbContext.SaveChangesAsync();

            return CreatedAtAction(nameof(GetCustomer), new { id = customer.Id }, customer);
        }

        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateCustomer(int id, Customer customer)
        {
            if (id != customer.Id)
            {
                return BadRequest();
            }

            _dbContext.Entry(customer).State = EntityState.Modified;

            try
            {
                await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!_dbContext.Customers.Any(c => c.Id == id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteCustomer(int id)
        {
            var customer = await _dbContext.Customers.FindAsync(id);

            if (customer == null)
            {
                return NotFound();
            }

            _dbContext.Customers.Remove(customer);
            await _dbContext.SaveChangesAsync();

            return NoContent();
        }
    }
}

最后,运行应用程序,并使用工具(例如Postman)测试增删改查操作。以下是一些示例请求的URL和请求体:

GET /api/customers:获取所有客户
GET /api/customers/{id}:根据ID获取客户
POST /api/customers:创建客户 请求体:
json
{
“name”: “John Doe”,
“email”: “john@example.com”
}
PUT /api/customers/{id}:更新客户 请求体:
json
{
“id”: 1,
“name”: “John Doe”,
“email”: “john.doe@example.com”
}
DELETE /api/customers/{id}:删除客户
希望这个示例能帮助你开始使用ASP.NET Core 6.0和Entity Framework Core进行增删改查操作。


http://www.niftyadmin.cn/n/4931852.html

相关文章

skynet 网络模块解析

文章目录 前言环境准备sneak peek线程数据结构会话对象&#xff1a;持有基础套接字&#xff0c;封装了套接字的基础操作。会话管理器&#xff1a;持有并管理会话池&#xff0c;给外部模块提供网络接口。 网络模块管理会话管理器的生命周期管理工作模式 总结技术点原子数据管道描…

原型和原型链理解

这个图大概能概括原型和原型链的关系 1.对象都是通过 _proto_ 访问原型 2.原型都是通过constructor 访问构造函数 3.原型是构造函数的 prototype 4.原型也是对象实例 也是通过 _proto_ 访问原型(Object.prototype) 5.Object.prototype的原型通过 _proto_ 访问 为null 那么…

“华为杯”研究生数学建模竞赛2018年-【华为杯】A题:关于跳台跳水体型系数设置的建模分析

目录 摘 要: 1.问题重述 1.1 问题背景 1.2 问题分析 2.模型假设和符号说明

PHP最简单自定义自己的框架model使用(七)

1、实现model使用效果 2、自动加载model,KJ.php //自动加载文件public static function _autoload($className){switch ($className){//自动model类case substr($className,-5)Model:$path MODEL./.$className..php;if(is_file($path)) include $path;break;//自动加载控制器…

构建之法 - 软件工程实践教学:一线教师的13问

福州大学单红老师的软工课程总结 2020春&#xff0c;不一样的学期不一样的软工实践 单红⽼师在总结中&#xff0c;提出了13条疑惑&#xff0c;《构建之法》的作者邹欣⽼师就单红⽼师提出的每⼀条疑惑&#xff0c;给出了⾃⼰的思考&#xff0c;与他进⾏探讨交流。欢迎你也来参与…

python --连接websocket

如果只是模拟js端发送接收的话&#xff0c;已经有了websocket server的话&#xff0c;只有client就好了 pip install websocket-client#-*- encoding:utf-8 -*-import sys sys.path.append("..") from socket import * import json, time, threading from websocket…

玄子Share - Java 开发之框架基础技术

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cfodZkLj-1691793219502)(./assets/%E7%8E%84%E5%AD%90Share%20-%20Java%20%E5%BC%80%E5%8F%91%E4%B9%8B%E6%A1%86%E6%9E%B6%E5%9F%BA%E7%A1%80%E6%8A%80%E6%9C%AF.png)] 玄子Share - Java 开发之框架…

13_Ansible role、创建目录结构、Roles依赖关系;Playbook参考资料:facts、with_item、jinja模板、role角色

16.Ansible role 16.1.Ansible Roles介绍 16.2.创建目录结构 16.3.Ansible Roles依赖关系 17.其它参考资料 17.1.Playbook参考资料 17.2.Ansible facts 17.3.判断语句 when 17.4.with_items 17.5.ansible jinja模板 17.6.ansible role角色 17.7.变量其它参考文档 16.Ansible r…