Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi All ,

I have the following method in in my c# project
C#
public string GetUser(){

var t = context.UsersTable.firstOrDefault(x =>x.Id = 2);
return t.Username


}


Just as simple as that ! but t is always null. user with id of 2 exists in the database i know that for a fact. What am i doing wrong?

What I have tried:

I ahve tried debugging and nowi 'm stuck but trying to understand on where i'm going wrong
Posted
Updated 7-Jun-16 5:16am
Comments
Karthik_Mahalingam 7-Jun-16 10:07am    
means UsersTable doesn't have the row with id as 2, check in database.
Richard Deeming 7-Jun-16 10:13am    
Either that's not the code you have in your project, or your project doesn't compile.

It's FirstOrDefault, not firstOrDefault; C# is case-sensitive.

You're missing a semi-colon on the return line.

And it should be x.Id == 2, not x.Id = 2. The equality operator requires two "=" signs.


Also, FirstOrDefault can return null if there are no matching items. If that happens, the return t.Username line will throw a NullReferenceException.
1Future 7-Jun-16 10:13am    
it does have the id of 2 . thats what weird
Karthik_Mahalingam 7-Jun-16 10:53am    
Apply breakpoint and Check the table rows count
CHill60 7-Jun-16 10:27am    
If you want to reply to a comment then use the "Reply" link so that the poster is notified

1 solution

As Richard said above, the code should be:
C#
public string GetUser()
{
    var t = context.UsersTable.FirstOrDefault(x => x.Id == 2);
    return t.Username;
}


Of course, this assumes you even have data in the UsersTable in your database AND it assumes there is a User in the UsersTable with an Id of 2.

This code also assumes that every row in the UsersTable in the database has a Username.

Your code also makes the assumption that an object is returned without checking for it. If there is no object returned from the database your return statement will throw a "NullReferenceExeception".

An updated version of the code:
C#
public string GetUser(int userId)
{
    var t = context.UsersTable.FirstOrDefault(x => x.Id == userId);

    if (t == null)
    {
        // Returns an empty string if no User was found. You may want to 
        // change this to something more appropriate or have it throw 
        // an Exception of some kind, depending on your business rules.
        return string.Empty; 
    }
    else
    {
        // Returns the Username of the located userId.
        return t.Username;
    }
}
 
Share this answer
 
v2
Comments
Matt T Heffron 7-Jun-16 12:21pm    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900