简体   繁体   中英

How do I check for a null value in a tuple or single value in a column using LINQ for Entity Framework?

I have a row that has a datetime value in it. If that value has a date, the user is confirmed and can log in. But, if the value is NULL, the user needs to find their confirmation email and click on the link to verify before log in.

I need to find out, using LINQ to EF, how to verify if that value in that row is NULL or not.

Here's what i have:

C#:

var verifiedquery = from q in db.applicants 
                    join r in db.UserActivations on q.id equals r.userID 
                    where q.ap_username.Equals(lgnUsers.UserName.Trim()) 
                    && q.ap_password.Equals(lgnUsers.Password) 
                    select r.dateVerified.Value;

if (!verifiedquery.Any())
{
    login.FailureText = "Confirm your account please.";
    e.Authenticated = false;
    return;
}

The problem is in your select:

select r.dateVerified.Value

You are getting the Value property of a nullable field. Instead you can just get your query to return a bool :

var isVerified = (from q in db.applicants 
                 join r in db.UserActivations on q.id equals r.userID 
                 where q.ap_username.Equals(lgnUsers.UserName.Trim()) 
                 && q.ap_password.Equals(lgnUsers.Password) 
                 && r.dateVerified.HasValue
                 select r.dateVerified)
    .Any();

You can get your nullable datetime variable, and then use this variable to check either it has value or not. Use following line of code,

var verifiedquery = from q in db.applicants 
                    join r in db.UserActivations on q.id equals r.userID 
                    where q.ap_username.Equals(lgnUsers.UserName.Trim()) 
                    && q.ap_password.Equals(lgnUsers.Password) 
                    select r.dateVerified;

if (!verifiedquery.HasValue)
{
    login.FailureText = "Confirm your account please.";
    e.Authenticated = false;
    return;
}

2 problems here:

1> from a query you get a list, you need to select only one (the first if you are sure that your query return only one result)

2> You want r.dateVerified, wich is a nullable dateTime, so that you can check if it's null or not after.

var verifiedquery = from q in db.applicants 
                        join r in db.UserActivations on q.id equals r.userID 
                        where q.ap_username.Equals(lgnUsers.UserName.Trim()) 
                        && q.ap_password.Equals(lgnUsers.Password) 
                        select r.dateVerified;
    var fstResult = verifiedQuery.First();
    if (!fstResult.HasValue)
    {
        login.FailureText = "Confirm your account please.";
        e.Authenticated = false;
        return;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM