ASP.NET Core应用程序1:创建示例项目

1 创建项目

创建一个MyWebApp的空项目。也可以用一下命令行创建。

dotnet new globaljson --sdk-version 3.1 --output MyWebApp
已成功创建模板“global.json file”。
dotnet new web --no-https --output MyWebApp --framework netcoreapp3.1
已成功创建模板“ASP.NET Core Empty”。
dotnet new sln -o MyWebApp
已成功创建模板“解决方案文件”。
dotnet sln MyWebApp add MyWebApp
已将项目“WebApp.csproj”添加到解决方案中。

2 添加数据模型

2.1 添加数据库NuGet包

Microsoft.EntityFrameworkCore.Design3.1.1版本

Microsoft.EntityFrameworkCore.SqlServer3.1.1版本

2.2 创建数据模型

在Models文件夹中创建三个类:Product、Supplier、Category。

/// <summary>
/// 产品
/// </summary>
public class Product
{
public long ProductId { get; set; }
public string Name { get; set; }
[Column(TypeName = "decimal(8, 2)")]
public decimal Price { get; set; }
public long CategoryId { get; set; }
public Category Category { get; set; }
public long SupplierId { get; set; }
public Supplier Supplier { get; set; }
}
/// <summary>
/// 供应商
/// </summary>
public class Supplier
{
public long SupplierId { get; set; }
public string Name { get; set; }
public string City { get; set; }
public IEnumerable<Product> Products { get; set; }
}
/// <summary>
/// 类别
/// </summary>
public class Category
{
public long CategoryId { get; set; }
public string Name { get; set; }
public IEnumerable<Product> Products { get; set; }
}

Models文件夹中创建一个能访问数据库的EFCore上下文类DataContext。

public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Category> Categories { get; set; }
}

2.3 准备种子数据

Models文件夹中创建SeedData类,用来定义填充的种子数据。

public static class SeedData
{
public static void SeedDatabase(DataContext context)
{
context.Database.Migrate();
if (context.Products.Count() == 0 && context.Suppliers.Count() == 0 &&
context.Categories.Count() == 0)
{
Supplier s1 = new Supplier { Name = "Splash Dudes", City = "San Jose" };
Supplier s2 = new Supplier { Name = "Soccer Town", City = "Chicago" };
Supplier s3 = new Supplier { Name = "Chess Co", City = "New York" };
Category c1 = new Category { Name = "Watersports" };
Category c2 = new Category { Name = "Soccer" };
Category c3 = new Category { Name = "Chess" };
context.Products.AddRange(
new Product { Name = "Kayak", Price = 275, Category = c1, Supplier = s1 },
new Product { Name = "Lifejacket", Price = 48.95m, Category = c1, Supplier = s1 },
new Product { Name = "Soccer Ball", Price = 19.50m, Category = c2, Supplier = s2 },
new Product { Name = "Corner Flags", Price = 34.95m, Category = c2, Supplier = s2 },
new Product { Name = "Stadium", Price = 79500, Category = c2, Supplier = s2 },
new Product { Name = "Thinking Cap", Price = 16, Category = c3, Supplier = s3 },
new Product { Name = "Unsteady Chair", Price = 29.95m, Category = c3, Supplier = s3 },
new Product { Name = "Human Chess Board", Price = 75, Category = c3, Supplier = s3 },
new Product { Name = "Bling-Bling King", Price = 1200, Category = c3, Supplier = s3 }
);
context.SaveChanges();
}
}
}

2.4 配置EFCore服务和中间件

对Startup类进行更改

public class Startup
{
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration config)
{
Configuration = config;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(opts =>
{
opts.UseSqlServer(Configuration["ConnectionStrings:ProductConnection"]);
opts.EnableSensitiveDataLogging(true);
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
SeedData.SeedDatabase(context);
}
}

在appsettings.json中定义配置字符串

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"Microsoft.EntityFrameworkCore": "Information"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"ProductConnection": "Server=.;Database=Products;MultipleActiveResultSets=true;User ID=sa;Pwd=123456;"
}
}

2.5 创建和应用迁移

在WebApp项目文件夹中运行命令

创建迁移 dotnet ef migrations add Initial

将迁移应用到数据库dotnet ef database update

如果需要重置数据库,可运行dotnet ef database drop -force

3 添加CSS框架

安装LibMan工具包 Microsoft.Web.LibraryManager.Cli2.0.96

命令

dotnet tool uninstall --global Microsoft.Web.LibraryManager.Cli
dotnet tool install --global Microsoft.Web.LibraryManager.Cli --version 2.0.96

安装引导CSS框架

命令

libman init -p cdnjs

libman install twitter-bootstrap@4.3.1 -d wwwroot/lib/twitter-bootstrap

或者在VS中选择添加客户端库

img

4 配置请求管道

定义一个简单中间件TestMiddleware.cs.

public class TestMiddleware
{
private RequestDelegate _nextDelegate;
public TestMiddleware(RequestDelegate nextDelegate)
{
_nextDelegate = nextDelegate;
}
public async Task Invoke(HttpContext context,DataContext dataContext)
{
if(context.Request.Path == "/test")
{
await context.Response.WriteAsync($"There are {dataContext.Products.Count()} products\n");
await context.Response.WriteAsync($"There are {dataContext.Categories.Count()} categories\n");
await context.Response.WriteAsync($"There are {dataContext.Suppliers.Count()} suppliers\n");
}
else
{
await _nextDelegate(context);
}
}
}

在Startup类中添加这个中间件组件

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DataContext context)
{
......
app.UseRouting();
app.UseMiddleware<TestMiddleware>();
......
}

5 运行项目

img

posted @   一纸年华  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
历史上的今天:
2018-04-01 数据库_mysql多表操作
点击右上角即可分享
微信分享提示

目录导航

1 创建项目
2 添加数据模型
2.1 添加数据库NuGet包
2.2 创建数据模型
2.3 准备种子数据
2.4 配置EFCore服务和中间件
2.5 创建和应用迁移
3 添加CSS框架
4 配置请求管道
5 运行项目