我正在使用以下代码在我的winform应用程序中登录用户
public static Boolean Attempt(String username, String password, bool salted = false)
{
using (InventorySystemEntities context = new InventorySystemEntities(new ConfigurationManager().ConnectionString))
{
password = password.ToMD5(salted);
User = context.Users.SingleOrDefault(u => u.UserName == username
&& u.Password == password && u.IsEnabled == true);
return User != null ? true : false;
}
}
是否有办法在处理完上下文后访问数据?比如使用新的上下文?
User test = Auth.Attempt(txtUsername.Text, txtPassword.Text);
//is there a way to access this?
test.UserGroup.Name;
答案 0 :(得分:1)
您可以使用显式加载来获取具有新上下文的导航属性:
public static void LoadUserGroup(User user)
{
using (InventorySystemEntities context = new InventorySystemEntities(
new ConfigurationManager().ConnectionString))
{
context.Users.Attach(user);
context.Entry(user).Reference(u => u.UserGroup).Load();
}
}
然后您可以访问UserGroup
:
User test = Auth.Attempt(txtUsername.Text, txtPassword.Text);
//...
Auth.LoadUserGroup(test);
test.UserGroup.Name;
如果不创建新的上下文,则无法导航到UserGroup
。