gpt4 book ai didi

c# - MVC5/EF6 : Object cannot be deleted because it was not found in the ObjectStateManager?

转载 作者:行者123 更新时间:2023-11-30 20:48:44 34 4
gpt4 key购买 nike

我的 MVC5 应用程序中有以下 HttpPost Delete() 方法。据我所知,与此 Controller 、 View 甚至模型相关的任何内容都没有改变。

    // POST: Admin/UserManagement/Delete/5
[HttpPost, ActionName("DeleteConfirmed")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(string id)
{
ApplicationUser applicationUser = db.Users.Find(id);
if (applicationUser == null)
{
ModelState.AddModelError("", "Failed to find User ID for deletion.");
}
else
{
IdentityResult result = await UserManager.DeleteAsync(applicationUser);
if (result.Succeeded)
{
await db.SaveChangesAsync();
return RedirectToAction("Index", "UserManagement");
}
else
{
ModelState.AddModelError("", "Failed to Delete User.");
var errors = string.Join(",", result.Errors);
ModelState.AddModelError("", errors);
}
}

return View(applicationUser);
}

用户管理器部分:

[CustomAuthorization(myRoles = "Admin")]
public class UserManagementController : Controller
{
protected ApplicationDbContext db { get; set; }
private ApplicationUserManager _userManager;

public UserManagementController()
{
this.db = new ApplicationDbContext();
}

public UserManagementController(ApplicationUserManager userManager)
{
UserManager = userManager;
}

public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}

当我的代码到达 IdentityResult result = await UserManager.DeleteAsync(applicationUser) 时,它立即跳转到我下面的 Dispose() 方法,而不是索引 View 加载,我得到:“/”应用程序中的服务器错误。
无法删除该对象,因为在 ObjectStateManager 中找不到它。

    protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();

if (UserManager != null)
{
UserManager.Dispose();
UserManager = null;
}
}
base.Dispose(disposing);
}

有人能告诉我哪里错了吗?我以前从未见过这个错误。以前此 DeleteConfirmed() 代码完全按预期工作。

编辑:

Startup.cs:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof(PROJECT.Startup))]
namespace PROJECT
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
}
}

EDIT2:

CustomAuthorization.cs(助手):

public class CustomAuthorization : AuthorizeAttribute
{
public string myRoles { get; set; }

public override void OnAuthorization(AuthorizationContext filterContext)
{
var userAuthInfo = HttpContext.Current.User;

if (userAuthInfo != null)
{
if (!userAuthInfo.Identity.IsAuthenticated)
{
string returnUrl = filterContext.HttpContext.Request.RawUrl;
filterContext.Result = new RedirectResult("/Account/Login?returnUrl=returnUrl");
return;
}

string[] roles = myRoles.Split(',');


var userAuth = false;

foreach (string role in roles)
{

if (userAuthInfo.IsInRole(role))
{
userAuth = true;
break;
}
}

if (!userAuth)
{
var result = new RedirectResult("/Home?auth=0");

filterContext.Result = result;
}
}
}
}

EDIT3

/App_Start/中的 Startup.Auth.cs:

public partial class Startup
{
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
app.CreatePerOwinContext(ApplicationDbContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}
}

解决方案 正如 haim770 指出的那样,我在我的 DeleteConfirmed() 操作方法中错误地使用了 2 个 DbContext 引用。

ApplicationUser applicationUser = db.Users.Find(id) 更改为正确的 async 并且一切都按预期工作:ApplicationUser applicationUser = await UserManager.FindByIdAsync( id);

感谢所有花时间提供帮助的人!

最佳答案

问题是您实际上在这里使用了 2 个 DbContext,它们无法跟踪彼此的实体。

您必须更改您的 Controller 代码,让 dbUserManager 共享相同的上下文实例引用:

public UserManagementController()
{
this.db = context.Get<ApplicationDbContext>();
}

关于c# - MVC5/EF6 : Object cannot be deleted because it was not found in the ObjectStateManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24271715/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com