PM> Install-Package Microsoft.EntityFrameworkCore.InMemory
public class Customer
{
public int Id { get; set; }
//保存不能为空,字符长度小于100
[Required, StringLength(100)]
public string Name { get; set; }
}
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Customer> Customers { get; set; }
}
public class Startup
{
public IHostingEnvironment HostingEnvironment { get; }
public void ConfigureServices(IServiceCollection services)
{
// 使用内存数据库
services.AddDbContext<AppDbContext>(options =>
options.UseInMemoryDatabase("name"));
services.AddMvc();
}
public void Configure(IApplicationBuilder app)
{
app.UseMvc();
}
}
@page
@model StudyRazorDemo.Pages.CreateModel
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
<html>
<body>
<p>
Enter your name.
</p>
<div asp-validation-summary="All"></div>
<form method="POST">
<!-- 这里的Customer对象来自后端-->
<div>Name: <input asp-for="Customer.Name" /></div>
<input type="submit" />
</form>
</body>
</html>
public class CreateModel : PageModel
{
private readonly AppDbContext _db;
public CreateModel(AppDbContext db)
{
_db = db;
}
//模型绑定,通过绑定使用相同的属性显示窗体字段<input asp-for="Customer.Name" />来减少代码,并接受输入,是双向绑定。
[BindProperty]
public Customer Customer { get; set; }
public async Task<IActionResult> OnPostAsync()
{
//验证Customer对象属性值
if (!ModelState.IsValid)
{
return Page();
}
//添加到EF上下文,再保存到内存数据库
_db.Customers.Add(Customer);
await _db.SaveChangesAsync();
// 重定向到index主页
return RedirectToPage("/Index");
}
}
<form method="post">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<!--Customers集合对象来自cs后端 -->
@foreach (var contact in Model.Customers)
{
<tr>
<td>@contact.Id</td>
<td>@contact.Name</td>
<td>
<a asp-page="./Edit" asp-route-id="@contact.Id">edit</a>
<button type="submit" asp-page-handler="delete"
asp-route-id="@contact.Id">
delete
</button>
</td>
</tr>
}
</tbody>
</table>
<a asp-page="./Create">Create</a>
</form>
public IList<Customer> Customers { get; private set; }
//代替OnGet方法
public async Task OnGetAsync()
{
//异步获取数据,EF上下文不跟踪该集合对象
Customers = await _db.Customers.AsNoTracking().ToListAsync();
}