【问题标题】:Error Db Context has been disposed错误 Db 上下文已被释放
【发布时间】:2014-01-27 11:05:38
【问题描述】:

好的,所以我不知道发生了什么以及为什么我不断收到我的数据库上下文已被处理的错误。让我告诉你我有什么然后引导你完成它。

控制器:

[HttpPost]
public ActionResult UserProfile(UserProfileViewModel model)
{
    bool success = false;
    var user = UserRepository.GetUserById((int)Session["UserId"]);

    success = user.FriendId == null
        ? FriendRepository.CreateUserProfile((int) Session["UserId"], model)
        : FriendRepository.UpdateUserProfile((int) Session["UserId"], model);

    if (!success) return View("UserProfile");

    UpdateSession((int) Session["UserId"]);
    return RedirectToAction("AddSteamQuestion", "Steam");
}

private void UpdateSession(int id)
{
    var user = UserRepository.GetUserById((int)Session["UserId"]);
    Session["UserFirstName"] = user.Friend.Alias;

}

所以首先它成功地抓取了用户。然后它在我的仓库中插入或更新用户配置文件。这似乎也很成功。最后它需要更新会话中的用户名(以防万一他们改变了它)。所以它跳到更新会话方法然后我得到抛出的错误?这不像 GetUserId 坏了,我在我的应用程序中大量使用它。事实上,它成功地在 UserProfile 方法中提取了第一个 var 用户的数据。

错误提示 DbContext 已被释放。

这是我为 GetUserById 疯狂的巨大回购(它在 var user = 上中断):

public UserModel GetUserById(int sessionId)
        {
            try
            {
                using (db)
                {
                    var user = (from u in db.Users
                                join f in db.Friends on u.FriendId equals f.Id
                                where u.Id == sessionId
                                select new UserModel()
                                {
                                    CreatedOn = u.CreatedOn,
                                    EmailAddress = u.EmailAddress,
                                    FriendId = u.FriendId,
                                    Id = u.Id,
                                    RoleId = u.RoleId,
                                    Friend = new FriendModel
                                    {
                                        Alias = f.Alias,
                                        CarrierId = f.CarrierId,
                                        CreatedOn = f.CreatedOn,
                                        FirstName = f.FirstName,
                                        Id = f.Id,
                                        LastName = f.LastName,
                                        Locked = f.Locked,
                                        PhoneNumber = f.PhoneNumber,
                                        SteamId = f.SteamId
                                    }

                                }).SingleOrDefault();
                    return user;
                }
            }
            catch (SqlException e)
            {
                throw new InvalidOperationException("Cannot Get User By Id", e);
            }
        }

【问题讨论】:

    标签: c# asp.net-mvc repository-pattern


    【解决方案1】:

    我认为您的db 是您的 dbContext 的私有字段,已被垃圾收集器处理,因此当您尝试访问 db.users 时,您将收到您所看到的错误。 我会这样写:

    using (var db = new YourDataContext()) {
        ...// do work here
    }
    

    用这个代替你的:

    using (db)
    

    这将确保正确创建和处置您的 DbContext。

    【讨论】:

    • 你是绝对正确的,它是在一个私人领域。使您的编辑工作。
    【解决方案2】:

    当您将对象放入using() 语句时,它会在退出块时“释放”该对象。这样对象就可以清理诸如数据库连接之类的东西。对象被释放后,将无法再使用,您需要创建一个新对象。

    看起来db 是您创建一次并持有的变量 - 但在using 语句处理它之后,它不能再次使用。修改您的代码,以便在每次访问数据库时创建一个新的数据上下文,如下所示:

    using (DatabaseContext db = new DatabaseContext())
    {
        ... // Do things here
    }
    

    每当您使用using 语句时,请在语句中声明对象。对于数据库事务尤其如此,因为如果您挂在相同的上下文中,稍后您可能会遇到并发和缓存的主要问题。保持您的上下文本地化,并在您完成事务后立即处理它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-26
      • 1970-01-01
      • 2016-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      相关资源
      最近更新 更多