Jupyter AI

21 数据访问之CRUD操作

📅 发表日期: 2024年8月15日

分类: 🌐ASP.NET Core 入门

👁️阅读: --

在上一篇中,我们讨论了如何进行数据库迁移以确保数据库的结构与我们应用程序中的实体类相匹配。本篇将重点讲解如何在ASP.NET Core应用程序中实现基本的CRUD(创建、读取、更新、删除)操作。

1. CRUD操作概述

CRUD是指对数据库中数据的基本操作,分别对应于以下四种功能:

  • 创建(Create):向数据库中添加新数据。
  • 读取(Read):从数据库中检索数据。
  • 更新(Update):修改已存在的数据。
  • 删除(Delete):从数据库中移除数据。

我们将通过一个简单的示例来实现对“用户”数据的CRUD操作。我们假设有一个名为User的实体,其具有IdNameEmail等属性。

2. 创建用户实体

首先,我们需要在项目中定义User实体。可以在Models文件夹中创建一个名为User.cs的文件,并添加以下代码:

public class User
{
    public int Id { get; set; }
    
    public string Name { get; set; }
    
    public string Email { get; set; }
}

3. 配置DbContext

接下来,我们需要在Data文件夹中创建一个ApplicationDbContext类,继承DbContext并配置我们的User实体。

using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<User> Users { get; set; }
}

然后,在Startup.cs中配置数据库上下文,确保已添加到ConfigureServices方法中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    services.AddControllersWithViews();
}

4. 创建CRUD控制器

现在我们将创建一个控制器UsersController来处理CRUD操作。在Controllers文件夹中添加UsersController.cs文件。

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

public class UsersController : Controller
{
    private readonly ApplicationDbContext _context;

    public UsersController(ApplicationDbContext context)
    {
        _context = context;
    }

    // GET: Users
    public async Task<IActionResult> Index()
    {
        return View(await _context.Users.ToListAsync());
    }

    // GET: Users/Create
    public IActionResult Create()
    {
        return View();
    }

    // POST: Users/Create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(User user)
    {
        if (ModelState.IsValid)
        {
            _context.Add(user);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(user);
    }

    // GET: Users/Edit/5
    public async Task<IActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users.FindAsync(id);
        if (user == null)
        {
            return NotFound();
        }
        return View(user);
    }

    // POST: Users/Edit/5
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(int id, User user)
    {
        if (id != user.Id)
        {
            return NotFound();
        }

        if (ModelState.IsValid)
        {
            try
            {
                _context.Update(user);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!UserExists(user.Id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
            return RedirectToAction(nameof(Index));
        }
        return View(user);
    }

    // GET: Users/Delete/5
    public async Task<IActionResult> Delete(int? id)
    {
        if (id == null)
        {
            return NotFound();
        }

        var user = await _context.Users
            .FirstOrDefaultAsync(m => m.Id == id);
        if (user == null)
        {
            return NotFound();
        }

        return View(user);
    }

    // POST: Users/Delete/5
    [HttpPost, ActionName("Delete")]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteConfirmed(int id)
    {
        var user = await _context.Users.FindAsync(id);
        _context.Users.Remove(user);
        await _context.SaveChangesAsync();
        return RedirectToAction(nameof(Index));
    }

    private bool UserExists(int id)
    {
        return _context.Users.Any(e => e.Id == id);
    }
}

5. 创建视图

接下来,我们需要为IndexCreateEditDelete操作创建视图。可以使用ASP.NET Core的Razor视图引擎来实现。

Views/Users文件夹下创建以下视图文件:

Views/Users/Index.cshtml

@model IEnumerable<User>

<h1>用户列表</h1>

<table class="table">
    <thead>
        <tr>
            <th>姓名</th>
            <th>Email</th>
            <th>操作</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var user in Model)
        {
            <tr>
                <td>@user.Name</td>
                <td>@user.Email</td>
                <td>
                    <a asp-action="Edit" asp-route-id="@user.Id">编辑</a> |
                    <a asp-action="Delete" asp-route-id="@user.Id">删除</a>
                </td>
            </tr>
        }
    </tbody>
</table>

<a asp-action="Create">创建新用户</a>

Views/Users/Create.cshtml

@model User

<h1>创建用户</h1>

<form asp-action="Create">
    <div class="form-group">
        <label asp-for="Name"></label>
        <input asp-for="Name" class="form-control" />
        <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="form-group">
        <label asp-for="Email"></label>
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
    <button type="submit" class="btn btn-primary">创建</button>
</form>

Views/Users/Edit.cshtml

@model User

<h1>