1

我正在使用下面的代码在我的 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;
4

1 回答 1

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.

于 2013-06-29T21:57:21.493 回答