I have a situation where a helper class with a static DBContext member is populating models’ boolean fields with different values than a non-static DBContext variable does. The latter is getting the correct variables.
In this case, I have a user with specified username in the database where “isAdmin” is set to true. The static member is returning a User object with isAdmin = false, the other is returning it with true as expected. See below.
Anyone know why this would happen?
Here is the model:
public class User
{
[Required]
public int UserID { get; set; }
[Required]
public string username { get; set; }
[Required]
public bool isAdmin { get; set; }
}
And the problematic helper class looks like this:
public static class UserAuthHelper
{
private static SSBPDContext db = new SSBPDContext();
public static User getUser(string username, string plaintextPassword)
{
var users = db.Users.Where(u => u.username.Equals(username));
User user = (from u in db.Users
where u.username.Equals(username)
select u).FirstOrDefault();
//this user has isAdmin = false
User otherUser;
using (var db2 = new SSBPDContext())
{
otherUser = (from u in db2.Users
where u.username.Equals(username)
select u).FirstOrDefault();
//otherUser has isAdmin = true
}
}
}
It happens because a DBContext caches the entities you request, so the next time you ask the same DBContext for the same entity it will just get it from memory, and not query the database again for it. As such, every change to that entity outside of that DBContext will be ignored.