如何使用实体框架和身份解决对象处置异常ASP.NET Core [英] How to resolve object disposed exception ASP.NET Core with Entity Framework and Identity
问题描述
我正在尝试编写一个控制器,该控制器从AJAX调用接收请求,并通过DBContext对数据库执行一些调用.但是,当我将命令var user = await GetCurrentUserAsynch();
放在对DBContext的任何调用之前时,如下所示,我得到一个ObjectDisposedException(无法访问已处置的对象).
I am trying to write a controller that receives a request from an AJAX call and performs some calls to the database via the DBContext. However, when I place the command var user = await GetCurrentUserAsynch();
in front of any calls to the DBContext, as shown below, I get an ObjectDisposedException (Cannot access a disposed object).
似乎UserManager和DBContext不能很好地配合使用,但是我在此问题上找不到很多信息.
It appears to be the UserManager and the DBContext not playing nicely together, however I can't find much information on the matter.
[HttpPost]
public async void EditUserMapItemAjax([FromBody]UserMapItemViewModel userMapItemViewModel)
{
var user = await GetCurrentUserAsync();
var mapItem = _db.MapItems.SingleOrDefault(x => x.Id == userMapItemViewModel.MapItemId);
...
}
private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);
推荐答案
将您的控制器操作声明为async Task
,而不是async void
.
Declare your controller action as async Task
, not async void
.
对于后者,一旦您的方法命中第一个await
,它将控制权返回给调用者,并且由于ASP.NET现在无法跟踪其进度(就像它返回
With the latter, as soon as your method hits the first await
, it returns control to the caller, and because ASP.NET now has no way to track its progress (as it would have when it returns a Task
instead), it disposes your controller instance, and (most-likely) along with it any locally-scoped fields.
尽管在那里,因为无论如何都处于异步方法中,所以您应该更喜欢EF调用的异步版本;即await _db.MapItems.SingleOrDefaultAsync()
While you're there, as you're in an async method anyway, you should prefer the async version of the EF call; i.e. await _db.MapItems.SingleOrDefaultAsync()
这篇关于如何使用实体框架和身份解决对象处置异常ASP.NET Core的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!