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.Design
3.1.1版本
Microsoft.EntityFrameworkCore.SqlServer
3.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.Cli
2.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 [email protected] -d wwwroot/lib/twitter-bootstrap
或者在VS中选择添加客户端库
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>();
......
}