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

C# 如何从数据库加载对象(实体框架),c#,entity-framework,crud,C#,Entity Framework,Crud,对于这个简单的用户类 public partial class Users { public long Id { get; set; } public string User { get; set; } public string Password { get; set; } } 我有WCF表单来添加新用户工作正常,并检查不允许重复的用户名 现在我有了一个用于登录的WCF表单,2个texbox(textBoxUser和passwo

对于这个简单的用户类

public partial class Users
{
        public long Id { get; set; }
        public string User { get; set; }
        public string Password { get; set; }        
}
我有WCF表单来添加新用户工作正常,并检查不允许重复的用户名

现在我有了一个用于登录的WCF表单,2个texbox(textBoxUser和password)和一个带有以下代码的按钮:

    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中发生类型为“System.ArgumentException”的未处理异常

其他信息:主键值之一的类型与实体中定义的类型不匹配。有关详细信息,请参见内部异常

即使User和textBoxUser.Text是字符串

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

您需要使用而不是

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

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

db.Users。首先(u=>u.User==textBoxUser.Text)
将以与
db.Users相同的方式返回该对象。任何(u=>u.User==textBoxUser.Text)
将在exists@Rafalon对,我已经得到了“MessageBox.Show”(“用户”+textBoxUser.Text+”存在!现在我需要检查密码是否正确。);“正在工作,但如何显示该对象的字段密码?检查我的答案以了解更多信息:)非常感谢。他现在正在工作。我来自讲西班牙语的国家,在Visual Studio中,我们没有处理单数和复数的选项,当然,我在本课的翻译上犯了一个错误。我的意思是,在创建实体模型时,我没有“复数化或单数化生成的对象名称”
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);
}