From 06c1b4140f6b7ff735e7738bba03e552dcc91d73 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?3=E7=8F=AD=E5=90=B4=E4=BD=B3=E6=95=8F?= <14125468+class-3-wu-jiamin@user.noreply.gitee.com> Date: Tue, 24 Dec 2024 19:31:16 +0800 Subject: [PATCH] =?UTF-8?q?1223=E7=AC=94=E8=AE=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...76\345\240\202\347\254\224\350\256\260.md" | 270 ++++++++++++++++++ 1 file changed, 270 insertions(+) create mode 100644 "\345\220\264\344\275\263\346\225\217/20241223\350\257\276\345\240\202\347\254\224\350\256\260.md" diff --git "a/\345\220\264\344\275\263\346\225\217/20241223\350\257\276\345\240\202\347\254\224\350\256\260.md" "b/\345\220\264\344\275\263\346\225\217/20241223\350\257\276\345\240\202\347\254\224\350\256\260.md" new file mode 100644 index 0000000..dcc8d7d --- /dev/null +++ "b/\345\220\264\344\275\263\346\225\217/20241223\350\257\276\345\240\202\347\254\224\350\256\260.md" @@ -0,0 +1,270 @@ +# MVC 数据库连接步骤笔记 +## 1. 项目初始化 + +首先,创建一个新的 MVC 项目。 +## 2. 添加必要的包和库 + +为了在 MVC 项目中连接数据库,通常需要使用 **Entity Framework (EF)**。可以通过 **NuGet 包管理器** 安装: + +1. 右键点击项目名称,选择 **管理 NuGet 程序包**。 +2. 在 **浏览** 选项卡中,搜索 **Entity Framework**。 +3. 选择 **Entity Framework** 包,点击 **安装**。 +4. 等待安装完成后,关闭包管理器窗口。 + +或者,使用 **Package Manager Console** 运行以下命令: + +```powershell +Install-Package EntityFramework +``` + +## 3. 配置数据库连接字符串 + +数据库连接字符串定义了应用程序如何连接到数据库。在 **Web.config** 文件中进行配置: + +1. 打开 **Web.config** 文件。 +2. 在 `` 节点下找到 `` 节点。如果不存在,可以手动添加。 +3. 添加连接字符串。例如,连接到 **SQL Server** 数据库: + +```xml + + + +``` + +**示例**: + +```xml + + + +``` + +## 4. 创建数据模型(Model) + +数据模型代表数据库中的表结构。在 **Models** 文件夹中创建一个新的模型类: + +1. 右键点击 **Models** 文件夹,选择 **添加** > **类**。 +2. 命名,例如 **Product.cs**,然后点击 **添加**。 +3. 定义模型属性。例如: + +```csharp +using System.ComponentModel.DataAnnotations; + +public class Product +{ + [Key] + public int Id { get; set; } + + [Required] + [StringLength(100)] + public string Name { get; set; } + + [Required] + [Range(0.01, 10000.00)] + public decimal Price { get; set; } + + public string Description { get; set; } +} +``` + +## 5. 创建数据库上下文(DbContext) + +**DbContext** 是 EF 提供的核心类,用于与数据库进行交互。在 **Models** 文件夹中创建一个新的上下文类: + +1. 右键点击 **Models** 文件夹,选择 **添加** > **类**。 +2. 命名,例如 **MyDbContext.cs**,然后点击 **添加**。 +3. 定义上下文类: + +```csharp +using System.Data.Entity; + +public class MyDbContext : DbContext +{ + // 构造函数,传递连接字符串名称 + public MyDbContext() : base("name=MyDbContext") + { + } + + // 定义 DbSet 属性,代表数据库中的表 + public DbSet Products { get; set; } +} +``` + +**注意**:`name=MyDbContext` 对应于 **Web.config** 中的连接字符串名称。 + +## 6. 配置数据库迁移 + +数据库迁移允许通过代码管理数据库架构的变化。以下是启用迁移的步骤: + +1. 打开 **Package Manager Console**。 +2. 选择 **默认项目** 为包含 **DbContext** 的项目。 +3. 运行以下命令以启用迁移: + +```powershell +Enable-Migrations +``` + +4. 创建初始迁移: + +```powershell +Add-Migration InitialCreate +``` + +5. 更新数据库: + +```powershell +Update-Database +``` + +**注意**:如果尚未创建数据库,**Update-Database** 将根据模型创建数据库。如果数据库已存在且包含数据,请谨慎操作。 + +## 7. 实现控制器(Controller) + +控制器负责处理用户请求,并与模型和视图进行交互。以下是创建 **ProductsController** 控制器的步骤: + +1. 右键点击 **Controllers** 文件夹,选择 **添加** > **控制器**。 +2. 选择 **MVC 5 控制器 - 空**,点击 **添加**。 +3. 命名,例如 **ProductsController**,点击 **添加**。 +4. 在控制器中定义动作方法。例如: + +```csharp +using System.Web.Mvc; +using MvcDatabaseConnection.Models; + +public class ProductsController : Controller +{ + private MyDbContext db = new MyDbContext(); + + // 显示产品列表 + public ActionResult Index() + { + var products = db.Products.ToList(); + return View(products); + } + + // 显示创建产品表单 + public ActionResult Create() + { + return View(); + } + + // 处理创建产品请求 + [HttpPost] + public ActionResult Create(Product product) + { + if (ModelState.IsValid) + { + db.Products.Add(product); + db.SaveChanges(); + return RedirectToAction("Index"); + } + return View(product); + } + + // 显示编辑产品表单 + public ActionResult Edit(int id) + { + var product = db.Products.Find(id); + if (product == null) + { + return HttpNotFound(); + } + return View(product); + } + + // 处理编辑产品请求 + [HttpPost] + public ActionResult Edit(Product product) + { + if (ModelState.IsValid) + { + db.Entry(product).State = EntityState.Modified; + db.SaveChanges(); + return RedirectToAction("Index"); + } + return View(product); + } + + // 删除产品 + public ActionResult Delete(int id) + { + var product = db.Products.Find(id); + if (product == null) + { + return HttpNotFound(); + } + db.Products.Remove(product); + db.SaveChanges(); + return RedirectToAction("Index"); + } + + // 释放资源 + protected override void Dispose(bool disposing) + { + if (disposing) + { + db.Dispose(); + } + base.Dispose(disposing); + } +} +``` + +## 8. 创建视图(View) + +视图负责呈现数据。以下是创建 **Index** 视图的步骤: + +1. 在 **Views** 文件夹下找到 **Products** 文件夹。如果没有,手动创建。 +2. 右键点击 **Products** 文件夹,选择 **添加** > **视图**。 +3. 选择 **List** 模板,点击 **添加**。 +4. 在 **Index.cshtml** 中,编辑视图以显示产品列表: + +```html +@model IEnumerable + +@{ + ViewBag.Title = "产品列表"; +} + +

产品列表

+ +

+ @Html.ActionLink("创建新产品", "Create") +

+ + + + + + + + + +@foreach (var item in Model) { + + + + + + +} +
+ @Html.DisplayNameFor(model => model.Name) + + @Html.DisplayNameFor(model => model.Price) + + @Html.DisplayNameFor(model => model.Description) +
+ @Html.DisplayFor(modelItem => item.Name) + + @Html.DisplayFor(modelItem => item.Price) + + @Html.DisplayFor(modelItem => item.Description) + + @Html.ActionLink("编辑", "Edit", new { id=item.Id }) | + @Html.ActionLink("删除", "Delete", new { id=item.Id }) +
\ No newline at end of file -- Gitee