EntityFramework中的SaveChanges()不保存更改。显示“功能评估需要所有线程运行”

问题描述 投票:0回答:2

以下是我的行动代码:

[HttpPost]
public ActionResult AddCategory(Models.CategoryViewModel category)
{
    try
    {
        if (ModelState.IsValid)
        {
            _context.Categories.Add(new Models.Category() { Name = category._Name });
            _context.SaveChanges();
        }
        var categories = _context.Categories.ToList();
        Models.CategoryViewModel categoryViewModel = new Models.CategoryViewModel()
        {
            _Category = categories.ToList(),
        };
        return View(categoryViewModel);
    }
    catch(Exception)
    {
        throw;
    }
}

我可以成功获取数据,但SaveChanges无法正常工作。我看到catch块中没有抛出任何异常,我在调试期间收到此错误:enter image description here

我在_context.Categories.Sql之前单击了线程图标,但它只显示了SELECT查询。

c# .net asp.net-mvc entity-framework ef-migrations
2个回答
1
投票

最后借助这个答案:https://stackoverflow.com/a/17055085/1124494我能够解决这个问题。虽然,我仍然无法理解这个问题。我正在使用一个通用控制器来获取ApplicationDbContext对象。我在基本控制器类中使用了这样的属性:

protected ApplicationDbContext _context { get { return new ApplicationDbContext(); } }

我在其他控制器中继承了这个类。我正确获取数据但无法保存。

当我在子类中声明ApplicationDbContext并使用他们自己的_context对象来保存数据时,它起作用了。

如果有人能告诉我为什么会这样,那么对于这个问题的未来访问者来说这将是一个很大的帮助。


0
投票

我想如果你将ApplicationDbcontext的protected更改为public,它可以工作,请告诉我它的对错,谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.