我做了一个简单的例子,先用EF Core代码创建数据库再查询数据,将值绑定到页面的过程如下。
1.第一个使用的依赖包如下:
型号:
public class ProductListView
{
[Key]
public Guid ID { get; set; }
public string ProductName { get; set; }
public double ProductPrice { get; set; }
}
我修改了您的 ProductPrice 类型,因为在迁移过程中这种类型会出现问题。如果必须更改类型,请参考这篇文章:
http://jameschambers.com/2019/06/No-Type-Was-Specified-for-the-Decimal-Column/
创建模型和上下文类:
现在您可以添加数据库上下文了
:将类命名为TestDbContext并点击Add,将TestDbContext.cs中的代码修改如下:
public class TestDbContext:DbContext
{
public TestDbContext(DbContextOptions<TestDbContext> options) : base(options)
{
}
public DbSet<ProductListView> productListViews { get; set; }
}
您需要在appsetting.json文件中写入如下连接字符串:
"ConnectionStrings": {
"DefaultDatabase": "Your DB"
}
在 ASP.NET Core 中,数据库上下文等服务必须注册到依赖注入容器中。容器为控制器提供服务。
使用以下突出显示的代码更新 Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<TestDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("DefaultDatabase")));
}
为了创建迁移代码,我们使用“add-migration MigrationName”命令。添加迁移命令执行成功后,会在项目中创建一个名为“Migration”的文件夹。我们只创建了负责创建数据库及其表的迁移。脚本。但是我们还没有创建实际的数据库和表。所以让我们执行迁移脚本并生成数据库和表。因此,要执行迁移脚本我们必须执行'update-database'命令。
接下来,让我们创建一个上下文类,定义数据库连接并注册上下文。然后在控制器中执行查询工作,然后返回数据。
public class TestController : Controller
{
private readonly TestDbContext _context;
public TestController(TestDbContext context)
{
_context = context;
}
public IActionResult Test(ProductListView product)
{
var value = _context.productListViews.SingleOrDefault(item => item.ProductPrice == 12.1);
product.ProductName = value.ProductName;
product.ProductPrice = value.ProductPrice;
return View(product);
}
}
查看:
@model WebApplication132.Models.ProductListView
<h1>AddProducts</h1>
<div class="row">
<div class="col-md-12">
<form method="post">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="ProductName"></label>
<input asp-for="ProductName" class="form-control" />
</div>
<div class="form-group">
<label asp-for="ProductPrice"></label>
<input asp-for="ProductPrice" class="form-control" />
</div>
<button type="Add Product" class="btn-primary">Add Product</button>
</form>
</div>
</div>
数据库数据:
结果: