Asp.Net Core 3.1 数据被检索但未保存到数据库中

Awa*_*eed 3 c# sql-server asp.net-core

我正在创建一个 Asp.Net 核心 Web 应用程序。我已成功将数据库连接到我的应用程序。我可以成功运行所有迁移,甚至可以从数据库中检索数据。但是当我尝试使用我的 DbContext 保存数据时,数据没有保存在数据库中。这是我的代码

类别模型类

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

类别控制器

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

看法

<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>
Run Code Online (Sandbox Code Playgroud)

数据库上下文类

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }

    public DbSet<Category> Categories { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

最后我在启动文件中的ConfigureServices 方法

public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();

        services.AddDbContext<AppDbContext>(options => options
        .UseLazyLoadingProxies()
        .UseSqlServer(Configuration.GetConnectionString("AppDbContext")));
    }
Run Code Online (Sandbox Code Playgroud)

我成功地在 Index 方法中获取了我手动存储在数据库中但无法从表单中保存的数据。

Ste*_*pUp 8

需要调用SaveChanges()EntityFramework的方法来保存数据:

dbContext.Categories.Add(category);
dbContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

SaveChanges创建、更新、删除操作后需要调用。