EF Code First模式下如何将Razor Page输入的产品数据插入SQL表
实现Razor Page插入产品数据到SQL数据表的操作步骤
1. 前置配置:准备数据库上下文
首先需要配置EF Core的数据库上下文来对接SQL数据库:
1.1 定义数据库上下文类
using Microsoft.EntityFrameworkCore; using Market.ViewModels; namespace Market.Data { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // 映射SQL中的产品表 public DbSet<ProductListView> Products { get; set; } } }
1.2 配置数据库连接
在appsettings.json中添加SQL连接字符串:
"ConnectionStrings": { "DefaultConnection": "Server=你的数据库地址;Database=MarketDb;Uid=账号;Pwd=密码;TrustServerCertificate=true" }
1.3 注入上下文服务
在Program.cs中注册数据库上下文服务:
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
1.4 初始化数据库表
执行EF Core迁移命令创建对应产品表:
- 包管理器控制台:
Add-Migration InitProductTable再执行Update-Database - dotnet CLI:
dotnet ef migrations add InitProductTable再执行dotnet ef database update
2. 编写Razor Page后端逻辑(.cshtml.cs文件)
在页面的后端代码中注入上下文,绑定模型,实现插入逻辑:
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Market.ViewModels; using Market.Data; namespace Market.Pages { public class CreateProductModel : PageModel { private readonly AppDbContext _context; public CreateProductModel(AppDbContext context) { _context = context; } // 绑定前端提交的产品数据 [BindProperty] public ProductListView Product { get; set; } public IActionResult OnGet() { // 手动生成产品ID,如果是数据库自增ID可省略该步骤 Product = new ProductListView { ID = Guid.NewGuid() }; return Page(); } // 处理表单提交的插入逻辑 public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } // 添加数据到上下文 _context.Products.Add(Product); // 异步保存到SQL数据库 await _context.SaveChangesAsync(); // 插入完成后跳转到产品列表页,可根据实际路由修改 return RedirectToPage("ProductList"); } } }
3. 编写Razor Page前端表单(.cshtml文件)
你原有的页面可参考下图结构:
前端表单代码示例:
@page @model Market.Pages.CreateProductModel <h3>新增产品</h3> <hr /> <div class="row"> <div class="col-md-4"> <form method="post"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <!-- ID不需要用户输入可设为隐藏域 --> <input type="hidden" asp-for="Product.ID" /> <div class="form-group"> <label asp-for="Product.ProductName" class="control-label"></label> <input asp-for="Product.ProductName" class="form-control" /> <span asp-validation-for="Product.ProductName" class="text-danger"></span> </div> <div class="form-group"> <label asp-for="Product.ProductPrice" class="control-label"></label> <input asp-for="Product.ProductPrice" class="form-control" /> <span asp-validation-for="Product.ProductPrice" class="text-danger"></span> </div> <div class="form-group"> <input type="submit" value="提交新增" class="btn btn-primary" /> </div> </form> </div> </div> @section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }
额外说明
- 如果你的产品ID需要由SQL自动生成,可在实体类的ID属性上添加
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]特性,无需手动赋值 - 可给模型属性添加验证特性,比如
[Required]、[Range(0.01,99999)],避免非法数据入库 - 不使用EF Core的情况下也可改用原生ADO.NET执行参数化INSERT语句实现插入,核心逻辑是获取前端提交的三个字段值传入SQL语句执行即可
内容的提问来源于stack exchange,提问作者Alexey chan
相关产品推荐
相关产品推荐

