如何从数据库(实体框架)加载对象



对于此简单的用户类

public partial class Users
{
        public long Id { get; set; }
        public string User { get; set; }
        public string Password { get; set; }        
}

我有WCF表单添加新用户工作正常并检查以不允许重复的用户名

现在,我有一个用于登录的WCF表单,2个TexBox(TextBoxuser和密码(和一个带有此代码的按钮:

    private void buttonOK_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("I want to validate the user and password");
        using (UserDBEntities db = new UserDBEntities())
        {
            if (db.Users.Any(o => o.User == textBoxUser.Text))
            {
                MessageBox.Show("The user " + textBoxUser.Text + " exist! Now I need to check if the password is right");
                var userAccepted = db.Users.Find(textBoxUser.Text);
            }
            else
                MessageBox.Show("User or password wrong. Try again!");
        }

但是线

var userAccepted = db.Users.Find(textBoxUser.Text);

不起作用 - 我一直遇到错误:

参数检查未经处理

在EntityFrameWork.dll

中发生了一个未经处理的例外。

附加信息:主要键值之一的类型与实体中定义的类型不匹配。有关详细信息,请参见内部例外。

即使用户和textboxuser.text是字符串。

我不知道如何从数据库加载对象,因此我可以检查密码是否可以。

您需要使用enumoser。

if (db.Users.Any(o => o.User == textBoxUser.Text))
{
    MessageBox.Show("The user " + textBoxUser.Text
                  + " exists! Now I need to check if the password is right");
    User userAccepted = db.Users.First(o => o.User == textBoxUser.Text);
    MessageBox.Show(userAccepted.Password);
}

我建议将您的Users定义更改为:

public partial class User // note it's User and not Users
{
    public long Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }        
}

然后答案将变成:

if (db.Users.Any(o => o.Username == textBoxUser.Text))
{
    MessageBox.Show("The user " + textBoxUser.Text
                  + " exists! Now I need to check if the password is right");
    User userAccepted = db.Users.First(o => o.Username == textBoxUser.Text);
    MessageBox.Show(userAccepted.Password);
}

因此,您避免了User类及其Username字段之间的混淆。(您也可以将其命名Name(

最新更新