如何从数据库加载对象 (Entity Framework)

How to load an object from the database (Entity Framework)

对于这个简单的用户 class

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

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

现在我有一个用于登录的 WCF 表单、2 个文本框(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);

不工作 - 我一直收到错误消息:

ArgumentException was unhandled

An unhandled exception of type 'System.ArgumentException' occurred in EntityFramework.dll

Additional information: The type of one of the primary key values did not match the type defined in the entity. See inner exception for details.

即使 User 和 textBoxUser.Text 是字符串。

而且我不知道如何从数据库加载对象,所以我可以检查密码是否正确。

您需要使用Enumerable.First instead of List<T>.Find

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 class 及其 Username 字段。 (你也可以直接命名为Name