Pavan Reddy Pavan Reddy - 6 months ago 18
SQL Question

how to write IsNull() in linq?

I want to write below query in linq.please help me.

SELECT ISNULL(userfirstname, '')userfirstname, useremail, usermobile FROM [user]
WHERE useremail='eeeee@gmail.com'

Answer
db.user.Where(u => u.useremail == "eeeee@gmail.com").
        Select(u => u.userfirstname ?? string.Empty);

This filters for your specified email and then projects the result by returning userfirtname or an empty string if userfirstname is null.


For your updated question:

db.user.Where(u => u.useremail == "eeeee@gmail.com").
        Select(u => new { 
             userfirstname = u.userfirstname ?? string.Empty,
             useremail = u.useremail,
             usermobile = u.usermobile});

This returns a sequence of instances of an anonymous type containing your values. You can create a data class for that too if you want:

public class MyUser
{
    public string userfirstname { get; set; }
    public string useremail { get; set; }
    public string usermobile { get; set; }
}

db.user.Where(u => u.useremail == "eeeee@gmail.com").
        Select(u => new MyUser { 
             userfirstname = u.userfirstname ?? string.Empty,
             useremail = u.useremail,
             usermobile = u.usermobile});