实体框架 - 空白数据仍添加到数据库中

时间:2013-07-26 05:17:23

标签: database entity-framework null

我已经进行了验证,以防止数据在空时插入数据库,但它仍然会将空白表单输入数据库?

protected void Button1_Click(object sender, EventArgs e)
    {
        ProjectTestEntities User_save = new ProjectTestEntities();
        User ins = new User();

        ins.name = TextBox1.Text;
        ins.email = TextBox2.Text;
        ins.phone = TextBox3.Text;
        ins.gender = RadioButtonList1.SelectedValue;
        ins.password = TextBox4.Text;

        if (ins.name == null || ins.email == null || ins.gender == null || ins.password == null)
        {
            Label1.Text = "Incomplete input";
        }
        else
        {
            User_save.Users.AddObject(ins);
            User_save.SaveChanges();
        }
    }

1 个答案:

答案 0 :(得分:1)

尝试使用string.IsNullOrEmpty()

if (string.IsNullOrEmpty(ins.name == null) || 
    string.IsNullOrEmpty(ins.email == null) ||
    string.IsNullOrEmpty(ins.gender == null) ||
    string.IsNullOrEmpty(ins.password == null))
{
    Label1.Text = "Incomplete input";
}
else
{
    User_save.Users.AddObject(ins);
    User_save.SaveChanges();
}