0

I have created a variable that checks if a row in a database exists. However when I put the variable in an if statement to check if it's null and the variable is null it always goes to else instead of continuing the if statement.

Is there another way of checking if a variable is null instead of == null?

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);
if (following == null)
{
    using (Html.BeginForm("Followruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="follow" class="btn btn-default" />
    }
}
else
{
    using (Html.BeginForm("unfollowruser", "Users"))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        @Html.Hidden("Id", Id)
        <input type="submit" value="following" class="btn btn-default" />
    }

}
0

4 Answers 4

3

The Where operator will never return null. It is also the wrong method to use if you simply want to check if a record exists. I'd use Any instead.

bool following = objCtx.Followusers.Any(
    c => c.User1ID == currentUser.Id || c.User2ID == cus.Id);
Sign up to request clarification or add additional context in comments.

Comments

2

Change it to:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).SingleOrDefault();

That should return NULL if no row is found.

1 Comment

An InvalidOperationException will be thrown if there are more than one records..
0

If you want to keep what you have given, you can also count number of values returned by the predicate.

if (following != null && following.Count < 1)

This should work for you I think.

Comments

0

The object returned is never null, it's value might be though. Use 'FirstOrDefault()' to make the result null if there is none:

var following = objCtx.Followusers.Where(c => c.User1ID == currentUser.Id || c.User2ID == cus.Id).FirstOrDefault();

Or ask the result if it has any values:

if(following.Any())

1 Comment

The query implies a bit that there could be multiple records in the result set. it might not be so, but FirstOrDefault(...) is a better idea than SingleOrDefault(...) here.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.