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

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

你可能感兴趣的:(.netcore,efcore)