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

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的文件,并添加以下代码:

csharp 复制代码
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的文件,并添加以下代码:

csharp 复制代码
namespace EFCoreDemo.Models
{
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

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

csharp 复制代码
{
  "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方法中添加以下代码,用于配置数据库上下文的依赖注入:

csharp 复制代码
services.AddDbContext<AppDbContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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

csharp 复制代码
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": "[email protected]"

}

PUT /api/customers/{id}:更新客户 请求体:

json

{

"id": 1,

"name": "John Doe",

"email": "[email protected]"

}

DELETE /api/customers/{id}:删除客户

希望这个示例能帮助你开始使用ASP.NET Core 6.0和Entity Framework Core进行增删改查操作。

相关推荐
CSharp精选营14 小时前
ASP.NET Core EFCore 属性配置与DbContext 详解
.net core·efcore·dbcontext
编程乐趣5 天前
基于.Net Core开发的GraphQL开源项目
后端·.netcore·graphql
吾门6 天前
机器视觉开发教程——C#如何封装海康工业相机SDK调用OpenCV/YOLO/VisionPro/Halcon算法
图像处理·opencv·计算机视觉·c#·.net·.netcore·visual studio
Kookoos7 天前
ABP vNext + EF Core 实战性能调优指南
数据库·后端·c#·.net·.netcore
[email protected]8 天前
ASP.NET Core 中实现 Markdown 渲染中间件
后端·中间件·asp.net·.netcore
吃瓜日常8 天前
ABP项目发布到IIS流程
c#·.netcore
[email protected]10 天前
ASP.NET Core 中间件
后端·中间件·asp.net·.netcore
[email protected]11 天前
ASP.NET Core 请求限速的ActionFilter
后端·asp.net·.netcore
菜鸟分享录12 天前
使用 Semantic Kernel 快速对接国产大模型实战指南(DeepSeek/Qwen/GLM)
microsoft·.netcore·semantic kernel
观无12 天前
Ocelot\Consul\.NetCore的微服务应用案例
.netcore·consul