VS web开发中连接数据库修改数据库通过.Add()进行数据插入
时间: 2024-03-02 18:51:45 浏览: 108
在 Visual Studio 中进行 Web 开发时,可以使用 ADO.NET 技术连接数据库并对数据库进行操作。下面是一些简单的示例代码,演示如何连接数据库并执行数据插入操作。
首先,需要在 Web 项目中添加连接数据库的相关引用。在解决方案资源管理器中,右键单击项目,选择“管理 NuGet 程序包”,然后搜索安装以下 NuGet 包:
- Microsoft.EntityFrameworkCore.SqlServer
- Microsoft.EntityFrameworkCore.Tools
接下来,需要在项目中创建一个数据库上下文类,该类将用于连接数据库并进行数据操作。可以使用 Entity Framework Core 来创建数据库上下文类。
```c#
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
}
}
```
在上面的代码中,`MyDbContext` 类继承自 `DbContext`,并且包含一个名为 `Customers` 的 `DbSet`,用于表示数据库中的 Customers 表。在 `OnConfiguring` 方法中,使用 `UseSqlServer` 方法指定要连接的 SQL Server 数据库。
接下来,可以在 Web 控制器中使用 `MyDbContext` 类来执行数据插入操作。例如,以下代码演示了如何添加一个新客户到 Customers 表中:
```c#
public class CustomersController : Controller
{
private readonly MyDbContext _context;
public CustomersController(MyDbContext context)
{
_context = context;
}
[HttpPost]
public IActionResult Create(Customer customer)
{
_context.Customers.Add(customer);
_context.SaveChanges();
return RedirectToAction(nameof(Index));
}
}
```
在上面的代码中,`CustomersController` 类包含一个名为 `Create` 的 POST 方法,用于接收表单数据并将新客户添加到数据库中。在方法中,使用 `_context.Customers.Add(customer)` 将新客户添加到 Customers 表中,然后使用 `_context.SaveChanges()` 将更改保存到数据库中。
以上是一个简单的示例,演示了如何在 ASP.NET Web 项目中连接数据库并执行数据插入操作。
阅读全文
相关推荐















