0

Login method:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login([Bind(Include = "Id,Mail,Pass")] LoginMember member)
    {
        if (!(ModelState.IsValidField("Mail") && ModelState.IsValidField("Pass")))
        {
            return View(login);
        }

        var areThere = db.LoginMember.Any(x => x.Mail == member.Mail && x.Sifre == member.Sifre);

        if (areThere)
        {
            var name = db.LoginMember.Where(x => x.Id == member.Id).Select(x => x.Name);

            Session["login"] = name;
            return RedirectToAction("Index", "Index");
        }
    }

This method is running, session is creating "Session["login"] = name;" and going to "return RedirectToAction("Index", "Index");".

Index view:

@{
    Layout = null;
}

@Session["login"]

<html>Index</html>

When Index view is running, has an error that is "System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.", what is the wrong?

tereško
  • 58,060
  • 25
  • 98
  • 150
Sss
  • 51
  • 2
  • 7

1 Answers1

3

I believe your problem lies here...

var name = db.LoginMember.Where(x => x.Id == member.Id).Select(x => x.Name);

the return value from Where and Select still holds a reference to the ObjectContext, remember that these extension methods are implemented by using deferred execution, the query is not executed until you enumerate it. Then when you save the IEnumarable object to a session variable and then "return" from the controller's action method, the ObjectContext is gargabe collected because supposedly it's no longer needed. So, basically once the view engine is rendering the Index view your session variable is holding a disposed object...hence the exception when you try to access it.

To fix the issue, you will need to "resolve" that Linq expression. I'd suggest using FirstOrDefault since you are only expecting one (and only one) user...

var user = db.LoginMember.FirstOrDefault(x => x.Id == member.Id);
var username = user != null ? user.Name : string.Empty;

the above is even safer and you can guarantee that if the user is not found FirstOrDefault will not throw an exception

Leo
  • 14,625
  • 2
  • 37
  • 55