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

标签 c# asp.net-mvc asp.net-mvc-5 entity-framework-6 objectstatemanager

我的 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/

相关文章:

两个应用程序共享一个配置文件的 c# 模式

c# - 如何在父窗口中相对于a控件的位置显示Modal窗体(opener)

javascript - 如何从特定选定行的事件发送者数据中获取模型数据?

asp.net-mvc - 自动 C# MVC 错误处理

asp.net-mvc-5 - 在 ASP.Net Core MVC Controller 中访问提交按钮的数据属性?

asp.net-mvc - 多个模型的 MVC 显示模板

c# - 立即停止线程

c# - 自动夹具 + NSubstitute : Freezing a mock?

javascript - 将 Base64 图像发布到 Mvc Controller

javascript - MVC5 与 Angular JS