c# – What is the most correct way to make a query with LINQ?

Question:

I'm trying to make a LINQ query in my SQL Server DB, but its result always comes 'null'. I need the first user ID I query on.

This is how I try to do the query:

public decimal GetCustomerBalance(long accountCurrentAdvisorId)
    {
        var result = this.Table.Select(x => x.AccountCurrentAdvisorId == accountCurrentAdvisorId);

        return result;
    }

Answer:

Need to do this:

public decimal GetCustomerBalance(long accountCurrentAdvisorId) {
    return this.Table.Where(x => x.AccountCurrentAdvisorId == accountCurrentAdvisorId)
                     .Select(x => x.CustomerBalance).First();
}

I put it on GitHub for future reference .

So you make a filter with Where , then select the information you want to get – I guessed that it would be CustomerBalance – and finally get the first result of the generated sequence (even if it already has only one element, after all you want an element and not one string containing an element, which are quite different data).

The likely internal query generated will look like this:

SELECT TOP 1 CustomerBalance FROM Table WHERE AccountCurrentAdvisorId = @accountCurrentAdvisorId
Scroll to Top