简介:本文将介绍如何使用ASP.NET Core创建一个Web API项目,并连接到SQL Server数据库进行数据操作。我们将通过实例展示如何创建数据库连接、定义数据模型、创建数据控制器以及实现数据增删改查等基本操作。
在开始之前,请确保您已经安装了以下软件和工具:
请将上述代码中的“你的服务器地址”、“你的数据库名称”、“你的用户名”和“你的密码”替换为实际的数据库连接信息。
{"ConnectionStrings": {"DefaultConnection": "Server=你的服务器地址;Database=你的数据库名称;User Id=你的用户名;Password=你的密码;Trusted_Connection=True;MultipleActiveResultSets=true"}}
在上述代码中,我们定义了一个名为Product的类,具有三个属性:Id、Name和Price。其中Id属性用于表示产品的唯一标识符。
public class Product{public int Id { get; set; }public string Name { get; set; }public decimal Price { get; set; }}
csharp
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{}
public DbSet<Product> Products { get; set; }
}在上述代码中,我们定义了一个名为ApplicationDbContext的类,继承自DbContext,并使用UseSqlServer扩展方法配置了数据库连接。同时定义了一个Products属性,用于表示数据库中的产品表。csharp
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")),\n ServiceLifetime.Transient);\n // ...其他配置代码...\n}\n在上述代码中,我们使用AddDbContext方法将ApplicationDbContext添加到服务提供者中,并指定使用SQL Server数据库连接字符串。