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

时间:2018-02-14 14:27:59

标签: 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和密码)以及一个包含此代码的按钮:

    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未处理

     

EntityFramework.dll中出现未处理的“System.ArgumentException”类型异常

     

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

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

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

1 个答案:

答案 0 :(得分:1)

您需要使用Enumerable.First代替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类与其Username字段之间的混淆。 (您也可以将其命名为Name