Asp.Net Core 3.1数据已检索但未保存到数据库中 [英] Asp.Net Core 3.1 Data is retrieved but not saved into database
问题描述
我正在创建一个Asp.Net核心Web应用程序.我已成功将数据库连接到我的应用程序.我可以成功运行所有迁移,甚至可以从数据库中检索数据.但是,当我尝试使用DbContext保存数据时,数据未保存在数据库中.这是我的代码
I am creating an Asp.Net core web application. I have successfully connected database to my app. I can run all the migration successfully and even retrieve data from database. But when I try to save data using my DbContext data is not saved in the database. Here is my code
类别模型类
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
类别控制器
public class CategoryController : Controller
{
private readonly AppDbContext dbContext;
public CategoryController(AppDbContext dbContext)
{
this.dbContext = dbContext;
}
[HttpGet]
public IActionResult Index()
{
var categories = dbContext.Categories.ToList();
return View(categories);
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create(Category category)
{
if (ModelState.IsValid)
{
dbContext.Categories.Add(category);
return RedirectToAction(nameof(Index));
}
return View();
}
}
查看
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
DbContext类
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
{
}
public DbSet<Category> Categories { get; set; }
}
最后是我的启动服务配置文件中的 ConfigureServices方法
and finally my ConfigureServices Method in Startup file
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<AppDbContext>(options => options
.UseLazyLoadingProxies()
.UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
}
我已成功通过Index方法成功获取了我已手动存储在数据库中但无法从表单保存的数据.
I successfully get data in the Index method that I have manually stored in database but cannot save from a form.
推荐答案
有必要调用EntityFramework的 SaveChanges()
方法来保存数据:
It is necessary to call SaveChanges()
method of EntityFramework to save data:
dbContext.Categories.Add(category);
dbContext.SaveChanges();
在创建,更新,删除操作之后,有必要调用 SaveChanges
.
It is necessary to call SaveChanges
after creating, updating, deleting operations.
这篇关于Asp.Net Core 3.1数据已检索但未保存到数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!