diff --git "a/\351\231\210\345\245\225\344\275\263/20241209mvc\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" "b/\351\231\210\345\245\225\344\275\263/20241209mvc\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" new file mode 100644 index 0000000000000000000000000000000000000000..9e4ad5113546922ebc771982e21ffd549963053d --- /dev/null +++ "b/\351\231\210\345\245\225\344\275\263/20241209mvc\346\225\260\346\215\256\345\272\223\350\277\236\346\216\245.md" @@ -0,0 +1,390 @@ +# ASP.NET MVC 中数据库连接笔记 + +## 1. 概述 + +在ASP.NET MVC应用程序中,数据库连接是实现数据持久化的关键部分。通常,使用Entity Framework(EF)作为ORM(对象关系映射)工具来简化数据库操作。EF提供了强大的功能来创建、读取、更新和删除(CRUD)数据库中的数据。 + +## 2. 数据库连接步骤概述 + +1. **创建数据库和表**: 使用SQL Server或其他数据库管理系统创建数据库和所需的表。 +2. **创建MVC项目**: 在Visual Studio中创建一个新的ASP.NET MVC项目。 +3. **安装Entity Framework**: 通过NuGet包管理器安装EF。 +4. **配置数据库连接字符串**: 在`Web.config`文件中配置数据库连接字符串。 +5. **创建数据模型**: 使用EF的Code First或Database First方法创建数据模型。 +6. **实现数据访问**: 在控制器中实现数据访问逻辑。 +7. **展示数据**: 在视图中展示从数据库获取的数据。 + +## 3. 详细步骤和代码示例 + +### 3.1 创建数据库和表 + +假设我们使用SQL Server,并创建一个名为`LinqPracticeDB`的数据库,包含一个`Customers`表。 + +```sql +CREATE DATABASE LinqPracticeDB; + +USE LinqPracticeDB; + +CREATE TABLE Customers ( + CustomerID INT IDENTITY(1,1) PRIMARY KEY, + Name NVARCHAR(100) NOT NULL, + Email NVARCHAR(100) NOT NULL, + Phone NVARCHAR(20) +); +``` + +### 3.2 创建MVC项目 + +在Visual Studio中创建一个新的ASP.NET MVC项目,选择“空”模板并添加MVC文件夹和核心引用。 + +### 3.3 安装Entity Framework + +使用NuGet包管理器安装Entity Framework。在“包管理器控制台”中运行以下命令: + +```powershell +Install-Package EntityFramework +``` + +### 3.4 配置数据库连接字符串 + +在`Web.config`文件中添加数据库连接字符串。例如: + +```xml + + + +``` + +### 3.5 创建数据模型 + +使用Code First方法创建数据模型。创建一个`Models`文件夹,并在其中创建`Customer.cs`: + +```csharp +using System.ComponentModel.DataAnnotations; + +namespace LinqPractice.Models +{ + public class Customer + { + [Key] + public int CustomerID { get; set; } + + [Required] + [StringLength(100)] + public string Name { get; set; } + + [Required] + [StringLength(100)] + public string Email { get; set; } + + [StringLength(20)] + public string Phone { get; set; } + } +} +``` + +创建数据库上下文`LinqPracticeDBContext.cs`: + +```csharp +using System.Data.Entity; + +namespace LinqPractice.Models +{ + public class LinqPracticeDBContext : DbContext + { + public LinqPracticeDBContext() : base("LinqPracticeDBContext") + { + } + + public DbSet Customers { get; set; } + } +} +``` + +### 3.6 实现数据访问 + +创建一个控制器`CustomersController.cs`来处理客户数据的CRUD操作。 + +```csharp +using System.Linq; +using System.Web.Mvc; +using LinqPractice.Models; + +namespace LinqPractice.Controllers +{ + public class CustomersController : Controller + { + private LinqPracticeDBContext db = new LinqPracticeDBContext(); + + // GET: Customers + public ActionResult Index() + { + var customers = db.Customers.ToList(); + return View(customers); + } + + // GET: Customers/Details/5 + public ActionResult Details(int id) + { + var customer = db.Customers.Find(id); + if (customer == null) + { + return HttpNotFound(); + } + return View(customer); + } + + // GET: Customers/Create + public ActionResult Create() + { + return View(); + } + + // POST: Customers/Create + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult Create(Customer customer) + { + if (ModelState.IsValid) + { + db.Customers.Add(customer); + db.SaveChanges(); + return RedirectToAction("Index"); + } + return View(customer); + } + + // GET: Customers/Edit/5 + public ActionResult Edit(int id) + { + var customer = db.Customers.Find(id); + if (customer == null) + { + return HttpNotFound(); + } + return View(customer); + } + + // POST: Customers/Edit/5 + [HttpPost] + [ValidateAntiForgeryToken] + public ActionResult Edit(Customer customer) + { + if (ModelState.IsValid) + { + db.Entry(customer).State = EntityState.Modified; + db.SaveChanges(); + return RedirectToAction("Index"); + } + return View(customer); + } + + // GET: Customers/Delete/5 + public ActionResult Delete(int id) + { + var customer = db.Customers.Find(id); + if (customer == null) + { + return HttpNotFound(); + } + return View(customer); + } + + // POST: Customers/Delete/5 + [HttpPost, ActionName("Delete")] + [ValidateAntiForgeryToken] + public ActionResult DeleteConfirmed(int id) + { + var customer = db.Customers.Find(id); + db.Customers.Remove(customer); + db.SaveChanges(); + return RedirectToAction("Index"); + } + + protected override void Dispose(bool disposing) + { + if (disposing) + { + db.Dispose(); + } + base.Dispose(disposing); + } + } +} +``` + +### 3.7 创建视图 + +在`Views/Customers`文件夹中创建以下视图: + +- **Index.cshtml**: 显示客户列表。 + +```html +@model IEnumerable + + + + + 客户列表 + + +

客户列表

+ + + + + + + + + + + + @foreach (var customer in Model) + { + + + + + + + + } + +
ID姓名电子邮件电话操作
@customer.CustomerID@customer.Name@customer.Email@customer.Phone + @Html.ActionLink("详情", "Details", new { id = customer.CustomerID }) | + @Html.ActionLink("编辑", "Edit", new { id = customer.CustomerID }) | + @Html.ActionLink("删除", "Delete", new { id = customer.CustomerID }) +
+

+ @Html.ActionLink("添加新客户", "Create") +

+ + +``` + +- **Create.cshtml**: 添加新客户。 + +```html +@model LinqPractice.Models.Customer + + + + + 添加新客户 + + +

添加新客户

+ @using (Html.BeginForm()) + { + @Html.AntiForgeryToken() +
+ @Html.LabelFor(m => m.Name) + @Html.TextBoxFor(m => m.Name) +
+
+ @Html.LabelFor(m => m.Email) + @Html.TextBoxFor(m => m.Email) +
+
+ @Html.LabelFor(m => m.Phone) + @Html.TextBoxFor(m => m.Phone) +
+ + } + + +``` + +- **Edit.cshtml**: 编辑客户信息。 + +```html +@model LinqPractice.Models.Customer + + + + + 编辑客户 + + +

编辑客户

+ @using (Html.BeginForm()) + { + @Html.AntiForgeryToken() + @Html.HiddenFor(m => m.CustomerID) +
+ @Html.LabelFor(m => m.Name) + @Html.TextBoxFor(m => m.Name) +
+
+ @Html.LabelFor(m => m.Email) + @Html.TextBoxFor(m => m.Email) +
+
+ @Html.LabelFor(m => m.Phone) + @Html.TextBoxFor(m => m.Phone) +
+ + } + + +``` + +- **Details.cshtml**: 显示客户详情。 + +```html +@model LinqPractice.Models.Customer + + + + + 客户详情 + + +

客户详情

+
+ ID: @Model.CustomerID +
+
+ 姓名: @Model.Name +
+
+ 电子邮件: @Model.Email +
+
+ 电话: @Model.Phone +
+

+ @Html.ActionLink("返回", "Index") +

+ + +``` + +- **Delete.cshtml**: 删除客户。 + +```html +@model LinqPractice.Models.Customer + + + + + 删除客户 + + +

删除客户

+

确定要删除客户 "@Model.Name" 吗?

+ @using (Html.BeginForm()) + { + @Html.AntiForgeryToken() + @Html.HiddenFor(m => m.CustomerID) + + } +

+ @Html.ActionLink("返回", "Index") +

+ + +``` \ No newline at end of file diff --git "a/\351\231\210\345\245\225\344\275\263/20241211Linq\346\237\245\350\257\242.md" "b/\351\231\210\345\245\225\344\275\263/20241211Linq\346\237\245\350\257\242.md" new file mode 100644 index 0000000000000000000000000000000000000000..2bf0b0a7f2870523834cec47056ec873bb29dc57 --- /dev/null +++ "b/\351\231\210\345\245\225\344\275\263/20241211Linq\346\237\245\350\257\242.md" @@ -0,0 +1,84 @@ +# MVC中LINQ查询 + +## 1. LINQ简介 + +LINQ(Language Integrated Query,语言集成查询)是微软为.NET Framework提供的一种查询技术,允许开发者在C#等语言中直接使用类似SQL的语法进行数据查询和操作。LINQ支持多种数据源,包括集合、数据库、XML等,并提供统一的查询语法。 + +## 2. LINQ查询的基本语法 + +### 2.1 查询表达式语法 + +LINQ查询表达式语法类似于SQL,常见结构如下: + +```csharp +var query = from item in dataSource + where condition + orderby item.Property ascending/descending + select item; +``` + +- **from**: 指定数据源和范围变量。 +- **where**: 过滤数据,返回满足条件的元素。 +- **orderby**: 对结果进行排序,可以指定升序(ascending)或降序(descending)。 +- **select**: 定义查询结果的形状或类型。 + +### 2.2 方法语法 + +方法语法使用扩展方法和Lambda表达式,常见方法包括: + +- **Where**: 过滤数据。 +- **Select**: 投影数据。 +- **OrderBy**: 排序数据。 +- **GroupBy**: 分组数据。 + +示例: + +```csharp +var query = dataSource.Where(item => item.Property > 10) + .OrderBy(item => item.Property) + .Select(item => item.Property); +``` + +## 3. LINQ查询操作符 + +### 3.1 常用操作符 + +- **Where**: 用于筛选数据。 +- **Select**: 用于选择和转换数据。 +- **OrderBy**: 用于排序数据。 +- **GroupBy**: 用于分组数据。 +- **Join**: 用于连接多个数据源。 + +### 3.2 聚合操作符 + +- **Sum**: 计算总和。 +- **Average**: 计算平均值。 +- **Count**: 计算元素数量。 +- **Max** 和 **Min**: 查找最大值和最小值。 + +## 4. LINQ查询的执行 + +### 4.1 延迟执行 + +LINQ查询默认采用延迟执行(Lazy Evaluation),即查询在定义时不立即执行,而是在迭代结果时才执行。这有助于提高性能,尤其是在处理大数据集时。 + +### 4.2 立即执行 + +可以使用诸如 `ToList()`, `ToArray()`, `Count()` 等方法来强制立即执行查询。这些方法会遍历查询结果并生成一个新的集合。 + +## 5. LINQ在MVC中的应用 + +在ASP.NET MVC中,LINQ常用于数据访问层(如Entity Framework)进行数据库操作。以下是一个简单的示例: + +```csharp +public ActionResult GetCustomers(string city) +{ + using (var db = new SampleDataContext()) + { + var customers = from c in db.Customers + where c.City == city + select c; + return View(customers.ToList()); + } +} +``` \ No newline at end of file diff --git "a/\351\231\210\345\245\225\344\275\263/20241213Linq\346\213\223\345\261\225\350\257\255\346\263\225.md" "b/\351\231\210\345\245\225\344\275\263/20241213Linq\346\213\223\345\261\225\350\257\255\346\263\225.md" new file mode 100644 index 0000000000000000000000000000000000000000..63dd05104e8c9595add2217974c8881e0cf8f13f --- /dev/null +++ "b/\351\231\210\345\245\225\344\275\263/20241213Linq\346\213\223\345\261\225\350\257\255\346\263\225.md" @@ -0,0 +1,57 @@ +## 标准查询操作符及例子 +这些是LINQ中最常用的扩展方法,它们被定义在System.Linq命名空间中。 + +1. Where - 筛选 + + List numbers = new List { 1, 2, 3, 4, 5 }; + var evenNumbers = numbers.Where(n => n % 2 == 0); // 筛选出偶数 + +2. Select - 投影 + + var squares = numbers.Select(n => n * n); // 将每个数字映射为其平方 + +3. SelectMany - 扁平化 + + List> a = new List> { + new List { 1, 2 }, + new List { 3, 4 } + }; + var b = a.SelectMany(list => list); // 将多个列表扁平化为一个列表 + +4. OrderBy/OrderByDescending - 排序 + + var c = numbers.OrderBy(n => n); // 升序排序 + var d= numbers.OrderByDescending(n => n); // 降序排序 + +5. GroupBy - 分组 + + var e= numbers.GroupBy(n => n % 2 == 0); // 根据数字是否为偶数进行分组 + +6. Aggregate - 聚合 + + int sum = numbers.Aggregate((total, n) => total + n); // 计算总和 + +7. Join - 联接 + + List f= new List { "apple", "banana", "cherry" }; + var g = words.Select(word => word.ToUpper()); // 将单词转换为大写 + var h = string.Join(", ", g); // 用逗号连接单词 + +辅助方法 +1. Count - 计数 + + int count = numbers.Count(); // 计算集合中的元素数量 + +2. Any/All - 存在/全部 + + bool hasEven = numbers.Any(n => n % 2 == 0); // 检查是否有偶数 + bool allPositive = numbers.All(n => n > 0); // 检查所有数字是否都大于0 + +3. Contains - 包含 + + bool containsThree = numbers.Contains(3); // 检查集合中是否包含数字3 + +4. DefaultIfEmpty - 默认值 + + IEnumerable emptyList = Enumerable.Empty(); + var defaultList = emptyList.DefaultIfEmpty(-1); // 如果集合为空,则返回-1