C#-在此上下文中仅支持原始类型或枚举类型

问题描述

我试图使登录页面连接到sql server,但是每当输入用户名和密码时,下一行代码

var user = db.Admins.Where(a => a.username.Equals(usertext)).SingleOrDefault();

引发下一个异常:

System.NotSupportedException:'无法创建常数 键入“ System.Windows.Forms.TextBox”。仅原始类型或 在此上下文中支持枚举类型。'

我应该如何解决

这是登录代码

AirlineEntities db = new AirlineEntities();
if (usertext.Text != string.Empty && passtext.Text != string.Empty) 
{
    var user = db.Admins.Where(a => a.username.Equals(usertext)).SingleOrDefault();
    if (user != null)
    {
        user.password.Equals(passtext);
        MessageBox.Show("Login successful");
    }
    else
    {
        MessageBox.Show("Incorrect password");
    }
}
else
{
    MessageBox.Show("Enter Username and Password please");
}

解决方法

您正在尝试将用户名与TextBox进行比较。您想将其与字符串进行比较,因此几乎可以肯定,您想再次使用Text属性。此外,您当前正在呼叫Equals作为密码,但是忽略了结果。我怀疑您想要类似的东西:

if (usertext.Text != string.Empty && passtext.Text != string.Empty) 
{
    var user = db.Admins.Where(a => a.username.Equals(usertext.Text)).SingleOrDefault();
    if (user != null && user.password.Equals(passtext.Text))
    {
        MessageBox.Show("Login successful");
    }
    else
    {
        // Note: message updated because we don't know whether the user
        // wasn't found,or they didn't have the right password
        MessageBox.Show("Incorrect user name or password");
    }
}

或更简单:

string user = usertext.Text;
string password = passtest.Text;

if (user != "" && password != "")
{
    var userEntity = db.Admins.SingleOrDefault(a => a.username == user);
    if (userEntity is object && userEntity.password == password)
    {
        MessageBox.Show("Login successful");
    }
    else
    {
        MessageBox.Show("Incorrect user name or password");
    }
}

还请注意,您似乎以纯文本形式存储密码,这非常安全性较弱。我强烈建议您使用开箱即用的身份系统,而不是像这样滚动自己的身份。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...