当前位置: 动力学知识库 > 问答 > 编程问答 >

asp.net mvc 3 - EF force model refresh after logout site

问题描述:

I have an issue with my model in EF model first. I have a web app, with security layer and entity layer and mvc3 layer. So in each layer I put a instance of my context db (one for each class in the main declaration section). the problem is when y find any user of my db for validate the login process, simple search, not make any changes in entity, is like this:

var usr = db.Usuarios.First(user => user.UserName.Equals(userName));

If I change the password for example in other layer (in my controller user), and the logout an login again, the linq search (see code up) always return the old password. This is for the context db dont dispose and dont go to database for the data, simple load the user for the model.

So, how I can force the model to refresh the data from the database?

I try, put lazy load in false but not work.

db.Configuration.LazyLoadingEnabled = false;

partial work if I decalre a instance of my context in the metod to validate passwork and dispose this instance, but I think it is the best practice.

like that:

 public static bool ValidateUser(string userName, string password)

{

if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))

{

var dbtmp = new ConorContainer();

var usr = dbtmp.Usuarios.First(user => user.UserName.Equals(userName));

if (usr != null)

{

var passDescrypt = Decript(usr.Password);

dbtmp.Dispose();

return passDescrypt.Equals(password);

}

return false;

}

return false;

}

网友答案:

You have to decide the lifetime of the context in each case. It is preferred to use short lived contexts in web applications specially in static methods.

Your method can be improved by employing the using block that will call the Dispose method when going out of scope.

public static bool ValidateUser(string userName, string password)
{
    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
    {
        using(var dbtmp = new ConorContainer())
        {

            var usr = dbtmp.Usuarios.First(user => user.UserName.Equals(userName));
            if (usr != null)
            {
                 var passDescrypt = Decript(usr.Password);
                 return passDescrypt.Equals(password);
            }
        }

        return false;
    }

    return false;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: