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

相关推荐
IT规划师6 小时前
C#|.net core 基础 - 扩展数组添加删除性能最好的方法
c#·.netcore·数组
时光追逐者7 小时前
分享6个.NET开源的AI和LLM相关项目框架
人工智能·microsoft·ai·c#·.net·.netcore
Lingbug21 小时前
.Net日志组件之NLog的使用和配置
后端·c#·.net·.netcore
IT规划师2 天前
C#|.net core 基础 - 值传递 vs 引用传递
c#·.netcore·值传递·引用传递
wenyinvjiuke2 天前
节日庆典中的白酒文化,传承与创新并存
.netcore
平凡而伟大(心之所向)3 天前
关于.net Framework向.net core的移植
java·.net·.netcore
时光追逐者3 天前
C#/.NET/.NET Core技术前沿周刊 | 第 5 期(2024年9.9-9.15)
microsoft·c#·.net·.netcore
世界太过浮夸6 天前
.net core 通过Sqlsugar生成实体
.netcore