Yesterday was not a good day, it seemed that I could not do a simple query that may have a null return. A few kind coders showed me where I was messing up. The funny thing about this is at one time I had it right. But for some unknown reason I failed to see it working when I tested it. So I moved on to trying to do it wrong again. lol I guess after seeing errors on every try I missed it when it worked.
So I want to show a simple example on how to handle a null return or I should say how I needed to handle it in my code. In t-sql we could always use the reader.HasRows but in Linq you need to use DefaultIfEmpty, SingleOrDefault, or one of the other Defaults.
registerDataContext db = new registerDataContext();
var users = (from user in db.userAccounts
where user.email == TextBox1.Text
select user).SingleOrDefault();
//Check if users is null.
if (users != null)
{
Label1.Text = string.Format("<h2>The email address <font color='red'>{0}</font> already exist!</h2>", TextBox1.Text);
}
else
{
Label1.Text = string.Format("<h2>The email address <font color='red'>{0}</font> does not exist!</h2>", TextBox1.Text);
}
Another way of making this same query is.
registerDataContext db = new registerDataContext();
userAccount users = db.userAccounts.SingleOrDefault(p => p.email == TextBox1.Text);
if (users != null)
{
Label1.Text = string.Format("<h2>The email address <font color='red'>{0}</font> is already exist!</h2>", TextBox1.Text);
}
else
{
Label1.Text = string.Format("<h2>The email address <font color='red'>{0}</font> does not exist!</h2>", TextBox1.Text);
}
I hope this may save someone else from pulling out their hair.