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进行增删改查操作。

相关推荐
刘梦凡呀1 天前
C# .NET Core 批量下载文件
windows·c#·.netcore
Zhen (Evan) Wang2 天前
.NET 6 WPF 利用CefSharp.Wpf.NETCore显示PDF文件
.net·wpf·.netcore
时光追逐者2 天前
C#/.NET/.NET Core拾遗补漏合集(25年4月更新)
c#·.net·.netcore
追雨潮2 天前
.net core 项目快速接入Coze智能体-开箱即用-第2节
.netcore
追雨潮3 天前
.net core 项目快速接入Coze智能体-开箱即用-全局说明
.netcore·ai编程
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 35 期(2025年4.14-4.20)
c#·.net·.netcore
全栈小54 天前
【C#】.net core 6.0调用MVC API接口时,提示Unsupported Media Type,状态码415
c#·mvc·.netcore
猫霸4 天前
理解.NET Core中的配置Configuration
html·.netcore·xhtml
MoFe14 天前
【.net core】【watercloud】数据库连接报错问题
数据库·.netcore
csdn_aspnet4 天前
Windows .NET Core 应用程序部署到 IIS 解决首次访问加载慢的问题
iis·.netcore