在本文中,我们将学习如何使用ASP.NET Core容器化和部署一个使用ASP.NET开发的数据库应用程序。
先决条件
- 安装Visual Studio 2022或更高版本
- 安装.NET SDK 6.0或更高版本
- 安装Docker Desktop
创建ASP.NET Core Web应用程序
- 在Visual Studio中,创建一个新的ASP.NET Core Web应用程序。
- 选择ASP.NET Core Web应用程序模板。
- 输入项目名称并单击“创建”。
添加Entity Framework Core
- 右键单击项目,然后选择“管理NuGet包”。
- 搜索并安装Microsoft.EntityFrameworkCore.SqlServer NuGet包。
创建数据模型
- 在项目中添加一个新的类,并将其命名为“Product”。
- 在“Product”类中添加以下属性:
“`csharppublic class Product{public int Id { get; set; }public string Name { get; set; }public decimal Price { get; set; }}“`
创建数据库上下文
- 在项目中添加一个新的类,并将其命名为“ProductContext”。
- 让“ProductContext”类继承自DbContext。
- 在“ProductContext”类中添加一个DbSet<Product>属性。
“`csharppublic class ProductContext : DbContext{public DbSet
配置数据库连接字符串
- 在appsettings.json文件中添加以下配置:
“`json{“ConnectionStrings”: {“DefaultConnection”: “Server=(localdb)\\MSSQLLocalDB;Database=MyDatabase;Trusted_Connection=True;”}}“`
更新Startup.cs
- 在Startup.cs文件中,添加以下代码以注册EF Core服务:
“`csharppublic void ConfigureServices(IServiceCollection services){// Add EF Core services.services.AddEntityFrameworkSqlServer();// Add the database context.services.AddDbContext
添加控制器和视图
- 在项目中创建一个新的控制器,并将其命名为“ProductController”。
- 在“ProductController”类中添加以下操作:
“`csharppublic class ProductController : Controller{private readonly ProductContext _context;public ProductController(ProductContext context){_context = context;}public IActionResult Index(){return View(_context.Products.ToList());}}“`
- 在项目中创建一个新的视图,并将其命名为“Index”。
- 在“Index”视图中添加以下代码:
@model IEnumerable
Id | Name | Price |
---|---|---|
@product.Id | @product.Name | @product.Price |
“`
构建和运行应用程序
- 构建解决方案。
- 在Visual Studio中运行应用程序。
容器化应用程序
- 在项目文件夹中创建一个名为“Dockerfile”的文件。
- 在“Dockerfile”文件中添加以下内容:
“`dockerfileFROM mcr.microsoft.com/dotnet/aspnet:6.0WORKDIR /appCOPY . /appRUN dotnet restoreRUN dotnet publish -c Release -o outFROM mcr.microsoft.com/dotnet/sdk:6.0WORKDIR /appCOPY . /appRUN dotnet restoreENTRYPOINT [“dotnet”, “out/Product.dll”]“`
部署容器
- 在项目文件夹中打开PowerShell窗口。
- 运行以下命令以构建容器映像:
“`powershelldocker build -t product .“`
- 运行以下命令以运行容器:
“`powershelldocker run -p 8080:80 product“`
结论
通过本文,我们了解了如何使用ASP.NET Core容器化和部署一个使用ASP.NET开发的数据库应用程序。我们创建了一个ASP.NET Core Web应用程序,添加了Entity Framework Core,配置了数据库连接字符串,并创建了控制器和视图。我们还创建了Dockerfile并部署了容器。