diff --git "a/\345\272\267\345\273\272\346\242\205/20241216--\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" "b/\345\272\267\345\273\272\346\242\205/20241216--\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" new file mode 100644 index 0000000000000000000000000000000000000000..173a9d07b7e582efeb3e302759287510527210e4 --- /dev/null +++ "b/\345\272\267\345\273\272\346\242\205/20241216--\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" @@ -0,0 +1,271 @@ +# 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** 中,编辑视图以显示产品列表: + +```c# +@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 diff --git "a/\345\272\267\345\273\272\346\242\205/20241218--\350\277\201\347\247\273\346\226\207\344\273\266.md" "b/\345\272\267\345\273\272\346\242\205/20241218--\350\277\201\347\247\273\346\226\207\344\273\266.md" new file mode 100644 index 0000000000000000000000000000000000000000..877744c1bdc63dd783e34a931151f161c6ae03eb --- /dev/null +++ "b/\345\272\267\345\273\272\346\242\205/20241218--\350\277\201\347\247\273\346\226\207\344\273\266.md" @@ -0,0 +1,10 @@ +1. 生成迁移文件,命令是:`dotnet er migrations add FirstInit` + +**前提条件:** +- 需要一个Design的依赖包,安装命令是:`dotnet add package Microsoft.EntityFrameworkCore.Design` +- 需要一个工具包,这个工具是`dotnet -ef`,全局安装的命令是:`dotnet tool install --global donet-ef` +- 程序不能有编译错误,使用`dotnet build`命令来排查编译错误 +- 程序不能处于运行状态 + + +2. 将上一步生成的迁移文件同步到数据库中,命令是:`dotnet er database update` \ No newline at end of file diff --git "a/\345\272\267\345\273\272\346\242\205/20241220--\345\242\236\345\210\240\346\224\271\346\237\245.md" "b/\345\272\267\345\273\272\346\242\205/20241220--\345\242\236\345\210\240\346\224\271\346\237\245.md" new file mode 100644 index 0000000000000000000000000000000000000000..f2a65eb5de7f40bedd5f64230ac21f09454954d9 --- /dev/null +++ "b/\345\272\267\345\273\272\346\242\205/20241220--\345\242\236\345\210\240\346\224\271\346\237\245.md" @@ -0,0 +1,106 @@ +# 新增 +```cs +@model Baby.Models.Babys; +
+
+
+
+ +
+``` +```cs +public IActionResult Create() + { + + return View(); + } + [HttpPost] + public IActionResult Create(Babys input) + { + var maxId=Db.Babys.Select(t=>t.Id).Max(); + input.Id=maxId+1; + Db.Babys.Add(input); + return RedirectToAction("Index"); + } + +``` +# 编辑 +```cs +public IActionResult Edit(int id) +{ + // 获取id + var baby = Db.Babys.FirstOrDefault(x => x.Id == id); + return View(baby); +} +[HttpPost] +public IActionResult Edit(Babys input) +{ + // 获取Id + var blog = Db.Babys.FirstOrDefault(x => x.Id == input.Id); + + if (blog != null) + { + blog.Title = input.Title; + blog.Content = input.Content; + blog.Author = input.Author; + } + return RedirectToAction("Index"); +} + +``` +# 删除 +```c# +public ActionResult Delete(int id) +{ + var product = db.Products.Find(id); + if (product == null) + { + return HttpNotFound(); + } + return View(product); +} +[HttpPost, ActionName("Delete")] +[ValidateAntiForgeryToken] +public ActionResult DeleteConfirmed(int id) +{ + var product = db.Products.Find(id); + if (product == null) + { + return HttpNotFound(); + } + db.Products.Remove(product); + db.SaveChanges(); + return RedirectToAction("Index"); +} +``` +# 查 +```c# +using System.Linq; +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 Details(int id) + { + var product = db.Products.Find(id); + if (product == null) + { + return HttpNotFound(); + } + return View(product); + } + + // 其他动作方法(Create, Edit, Delete)... +} +``` \ No newline at end of file