"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=MyDB;Trusted_Connection=True;"
}
在IIS中创建应用程序池和网站,并设置应用程序池的.NET CLR版本和托管管道模式。例如,将版本设置为.NET CLR版本为No Managed Code,托管管道模式为Integrated。
将项目发布到本地文件夹中,例如'C:\PublishOutput'。
在IIS中添加站点,将网站物理路径设置为步骤3中发布的文件夹路径。
将应用程序池设置好并关联到站点。
设置站点的应用程序池的标识为'LocalSystem',以确保具有足够的权限来访问数据库。
将数据库符合步骤1中设置的连接字符串连接到服务器上。
重新启动IIS,以确保站点已部署并能够连接到数据库。
例如,以下代码示例演示了如何使用Entity Framework Core来连接到数据库并查询数据。
using Microsoft.EntityFrameworkCore;
namespace MyNamespace.Models
{
public class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions options) : base(options)
{
}
public DbSet MyModels { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity().ToTable("MyModel");
base.OnModelCreating(modelBuilder);
}
}
public class MyModel
{
public int Id { get; set; }
public string Name { get; set; }
}
}
在Startup.cs中添加以下代码以注册DbContext:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
接下来可以在Controller中使用MyDbContext来查询数据: