使用 EntityFrameworkCore 的 ASP.NET Core Mvc (.NET 6) CRUD 操作

介绍

在本教程中,我们将创建一个项目来使用 Microsoft Asp .NET Core 6 和 EntityFrameworkCore 执行 CRUD 操作。我们在本教程中使用 Visual Studio 2022 和 MS SQL 或MySQL服务器。

目录
  1. 使用 EntityFrameworkCore 的 ASP.NET Core Mvc (.NET 6) CRUD 操作
  2. 介绍
  3. 我们将要学习什么...... – Glimpse
  4. 打开 Visual Studio 并单击创建新项目
  5. 选择 ASP.NET Core Web App (Model-View-Controller) – [C#] 并点击下一步按钮
  6. 输入项目名称,然后单击下一步按钮
  7. 选择 .Net 6.0 ,身份验证类型 None 并单击创建按钮
  8. 创建后,您的项目将如下所示
  9. 打开 Models 文件夹并创建一个 Employee 类
  10. 根据您的 .NET Core 版本安装以下包
  11. 创建 DBContext 类的子类 ApplicationDbContext 以链接数据库和数据模型类
  12. 打开 appsettings.json 并配置连接字符串
  13. 打开 program.cs 文件并添加所需的服务
  14. 运行迁移
    1. 迁移文件
  15. 运行以下更新命令以根据此迁移文件更新数据库
  16. 迁移后的数据库视图
  17. 添加员工控制器
    1. 将以下代码粘贴到您的 EmployeeControler.cs 文件中
  18. 添加视图文件
    1. Index.cshtml 代码
    2. 创建.cshtml
    3. 编辑.cshtml
    4. 删除.cshtml
    5. 留下回复 取消回复
    6. 相关文章
      1. 带有 Bootstrap 5 的最佳 Laravel 8 CRUD 教程

开始吧

第1步

打开 Visual Studio 并单击创建新项目

第2步

选择 ASP.NET Core Web App (Model-View-Controller) – [C#] 并点击下一步按钮

步骤 - 3

输入项目名称,然后单击下一步按钮

第四步

选择 .Net 6.0 ,身份验证类型 None 并单击创建按钮

创建后,您的项目将如下所示

步骤 - 5

打开 Models 文件夹并创建一个 Employee 类

在员工类中输入以下代码

using System.ComponentModel.DataAnnotations;

namespace EmployeeCRUD.Models
{
    public class Employee
    {
        [Key]
        public int Id { get; set; }
        [Required]
        [Display(Name ="Employee Name")]
        public string Name { get; set; }
        public string Designation { get; set; }
        [DataType(DataType.MultilineText)]
        public string Address { get; set; }        
        public DateTime? RecordCreatedOn { get; set; }

    }
}

步骤 - 6

根据您的 .NET Core 版本安装以下包

 <PackageReference Include="Microsoft.EntityFrameworkCore" Version="6.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="6.0.1">
    <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="6.0.1" />

步骤 - 7

创建一个子类ApplicationDbContext of DBContext Class来链接数据库和数据模型类

  1. 创建一个文件夹并将其命名为 Data

  1. 创建 ApplicaitonDbContext 类并输入以下代码
using EmployeeCRUD.Models;
using Microsoft.EntityFrameworkCore;

namespace EmployeeCRUD.Data
{
    public class ApplicationDbContext:DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
        {

        }

        public DbSet<Employee> Employees { get; set; }
    }
}

在上面的代码中,我们使用构造函数传递参数 DbContextOptions<ApplicationDbContext>,使用它我们将上下文配置从 AddDbContext 传递到 DbContext

步骤 - 8

打开 appsettings.json 并配置连接字符串

appsettings.json 文件的以下代码带有示例数据。根据您的系统或开发环境设置替换示例数据。

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=EnterServerName; Database=EmployeeDatabase; User Id=sa; Password=EnterPassword; Trusted_Connection=True; MultipleActiveResultSets=true"
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

使用MySQL时,文件内容如下:

{
  "ConnectionStrings": {
    "DefaultConnection": "server=localhost;user=root;database=customerdb;port=3306;password=root"
  },

  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

步骤 - 9

打开 program.cs 文件并添加所需的服务

  1. 将 ApplicationDbContext 子类注册为应用程序服务提供者/依赖注入容器中的范围服务。
  2. 输入以下代码行注册ApplicaitonDbContext
// add
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
        ));

使用MySQL时,文件内容如下:

// add
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseMySql(
        builder.Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection")))
        );

Program.cs 文件

using EmployeeCRUD.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// add
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseSqlServer(
        builder.Configuration.GetConnectionString("DefaultConnection")
        ));


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

使用MySQL时,文件内容如下:

using EmployeeCRUD.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();

// add
builder.Services.AddDbContext<ApplicationDbContext>(
    options => options.UseMySql(
        builder.Configuration.GetConnectionString("DefaultConnection"), ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("DefaultConnection")))
        );


var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

步骤 - 10

运行迁移

  1. 打开包管理器控制台

键入以下命令以运行迁移

add-migration 'initial'

迁移文件

以下是迁移文件的代码。您可以在 Migration 文件夹下找到此文件 (20220109062010_initial.cs)

using System;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace EmployeeCRUD.Migrations
{
    public partial class initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("SqlServer:Identity", "1, 1"),
                    Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Designation = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
                    RecordCreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Employees", x => x.Id);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");
        }
    }
}

使用MySQL时,文件内容如下:

using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace EmployeeCRUD.Migrations
{
    public partial class initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AlterDatabase()
                .Annotation("MySql:CharSet", "utf8mb4");

            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    Id = table.Column<int>(type: "int", nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(type: "longtext", nullable: false)
                        .Annotation("MySql:CharSet", "utf8mb4"),
                    Designation = table.Column<string>(type: "longtext", nullable: false)
                        .Annotation("MySql:CharSet", "utf8mb4"),
                    Address = table.Column<string>(type: "longtext", nullable: false)
                        .Annotation("MySql:CharSet", "utf8mb4"),
                    RecordCreatedOn = table.Column<DateTime>(type: "datetime(6)", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Employees", x => x.Id);
                })
                .Annotation("MySql:CharSet", "utf8mb4");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");
        }
    }
}

步骤 - 11

运行以下更新命令以根据此迁移文件更新数据库

update-database

迁移后的数据库视图

步骤 - 12

添加员工控制器

  1. 右键单击员工文件夹
  2. 点击添加
  3. 点击控制器

4. 选择 MVC Controller Empty 并点击 Add 按钮

5.输入控制器名称并按添加按钮

步骤 - 13

将以下代码粘贴到您的 EmployeeControler.cs 文件中

using EmployeeCRUD.Data;
using EmployeeCRUD.Models;
using Microsoft.AspNetCore.Mvc;

namespace EmployeeCRUD.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly ApplicationDbContext _context;
        public EmployeeController(ApplicationDbContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
            IEnumerable<Employee> objCatlist = _context.Employees;
            return View(objCatlist);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Employee empobj)
        {
            if (ModelState.IsValid)
            {
                _context.Employees.Add(empobj);
                _context.SaveChanges();
                TempData["ResultOk"] = "Record Added Successfully !";
                return RedirectToAction("Index");
            }

            return View(empobj);
        }

        public IActionResult Edit(int? id)
        {
            if (id == null || id == 0)
            {
                return NotFound();
            }
            var empfromdb = _context.Employees.Find(id);

            if (empfromdb == null)
            {
                return NotFound();
            }
            return View(empfromdb);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Edit(Employee empobj)
        {
            if (ModelState.IsValid)
            {
                _context.Employees.Update(empobj);
                _context.SaveChanges();
                TempData["ResultOk"] = "Data Updated Successfully !";
                return RedirectToAction("Index");
            }

            return View(empobj);
        }

        public IActionResult Delete(int? id)
        {
            if (id == null || id == 0)
            {
                return NotFound();
            }
            var empfromdb = _context.Employees.Find(id);
         
            if (empfromdb == null)
            {
                return NotFound();
            }
            return View(empfromdb);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult DeleteEmp(int? id)
        {
            var deleterecord = _context.Employees.Find(id);
            if (deleterecord == null)
            {
                return NotFound();
            }
            _context.Employees.Remove(deleterecord);
            _context.SaveChanges();
            TempData["ResultOk"] = "Data Deleted Successfully !";
            return RedirectToAction("Index");
        }


    }
}

步骤 - 14

添加视图文件

在View文件夹下创建一个Employee文件夹,并创建如下文件

  1. 索引.cshtml
  2. 创建.cshtml
  3. 编辑.cshtml
  4. 删除.cshtml

Index.cshtml 代码

@model IEnumerable<Employee>

    @{
    ViewData["Title"] = "Index";
}

@if (TempData["ResultOk"] != null)
{
    <h1 class="alert-success">@TempData["ResultOk"]</h1>
}

<div class="container shadow p-5">

    <h1 class="text-center mb-3">CRUD Operations Using .NET Core 6 & Microsoft.EntityFrameworkCore </h1>

    <div class="col mb-3">
        <a asp-controller="Employee" asp-action="Create" class="btn btn-lg btn-primary"><i class="bi bi-file-plus-fill"></i>Add Employee</a>
    </div>
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th scope="col">Employee Name</th>
                <th scope="col">Designation</th>
                <th scope="col">Address</th>
                <th scope="col">CreatedOn</th>
                <th></th>
            </tr>
        </thead>
        <tbody>

            @foreach (var item in Model)
            {
                <tr>
                    <td width="20%">
                        @item.Name
                    </td>
                    <td width="20%">
                        @item.Designation
                    </td>
                    <td width="25%">
                        @item.Address
                    </td>
                    <td width="20%">
                        @item.RecordCreatedOn
                    </td>
                    <td>
                        <div role="group" class="w-60 btn-group">
                            <a asp-controller="Employee" asp-action="Edit" asp-route-id="@item.Id" class=" btn btn-sm btn-primary"><i class="bi bi-pencil-square"></i>Edit</a>&nbsp;
                            <a asp-controller="Employee" asp-action="Delete" asp-route-id="@item.Id" class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i>Delete</a>
                        </div>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</div>

Create.cshtml

@model Employee


<div class="container shadow p-5">
    <div class="row pb-2">
        <h2>Add Employee</h2>
    </div>

    <form method="post">
        <div asp-validation-summary="All"></div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Name">Employee Name</label>
                <input type="text" class="form-control mb-3" asp-for="Name" placeholder="Enter Name">
                <span asp-validation-for="Name" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6">
                <label asp-for="Designation">Designation</label>
                <input type="text" class="form-control mb-3" asp-for="Designation" placeholder="Enter Designation">
                <span asp-validation-for="Designation" class=" alert-danger"></span>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Address">Address</label>
                <input type="text" class="form-control mb-3" asp-for="Address" placeholder="Enter Address">
                <span asp-validation-for="Address" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6 mb-3">
                <label asp-for="RecordCreatedOn">Created On</label>
                <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn">
                <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
            </div>
        </div>


        <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Save</button>
        <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
    </form>

</div>


@*//for front end validations*@

@section Scripts{
    @{
    <partial name="_ValidationScriptsPartial" />
    }
}

Edit.cshtml

@model Employee

<div class="container shadow p-5">
    <div class="row pb-2">
        <h2>Edit Employee</h2>
    </div>

    <form method="post" asp-action="Edit">
        <div asp-validation-summary="All"></div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Name">Employee Name</label>
                <input type="text" class="form-control mb-3" asp-for="Name">
                <span asp-validation-for="Name" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6">
                <label asp-for="Designation">Designation</label>
                <input type="text" class="form-control mb-3" asp-for="Designation">
                <span asp-validation-for="Designation" class=" alert-danger"></span>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Address">Address</label>
                <input type="text" class="form-control mb-3" asp-for="Address">
                <span asp-validation-for="Address" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6 mb-3">
                <label asp-for="RecordCreatedOn">Created On</label>
                <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn">
                <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
            </div>
        </div>


        <button type="submit" class="btn btn-lg btn-primary p-2"><i class="bi bi-file-plus-fill"></i>Update</button>
        <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
    </form>

</div>


@*//for front end validations*@

@section Scripts{
    @{
    <partial name="_ValidationScriptsPartial" />
    }
}

Delete.cshtml

@model Employee

<div class="container shadow p-5">
    <div class="row pb-2">
        <h2>Delete Employee</h2>
    </div>

    <form method="post" asp-action="DeleteEmp">
        <input asp-for="Id" hidden />
        <div asp-validation-summary="All"></div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Name">Employee Name</label>
                <input type="text" class="form-control mb-3" asp-for="Name" disabled>
                <span asp-validation-for="Name" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6">
                <label asp-for="Designation">Designation</label>
                <input type="text" class="form-control mb-3" asp-for="Designation" disabled>
                <span asp-validation-for="Designation" class=" alert-danger"></span>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group col-md-6">
                <label asp-for="Address">Address</label>
                <input type="text" class="form-control mb-3" asp-for="Address" disabled>
                <span asp-validation-for="Address" class=" alert-danger"></span>
            </div>
            <div class="form-group col-md-6 mb-3">
                <label asp-for="RecordCreatedOn">Created On</label>
                <input type="datetime-local" class="form-control" asp-for="RecordCreatedOn" disabled>
                <span asp-validation-for="RecordCreatedOn" class=" alert-danger"></span>
            </div>
        </div>
         

        <button type="submit" class="btn btn-lg btn-danger p-2"><i class="bi bi-trash-fill"></i>Delete</button>
        <a asp-controller="Employee" asp-action="Index" class="btn btn-lg btn-warning p-2">Back To List</a>
    </form>

</div>


@*//for front end validations*@

@section Scripts{
    @{
    <partial name="_ValidationScriptsPartial" />
    }
}

步骤 - 15

最后运行应用程序并测试所有功能

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值