What is the most correct way to query with LINQ?

10

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

This is the way I try to query it:

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

        return result;
    }
    
asked by anonymous 11.04.2015 / 05:46

3 answers

9

You need to do this:

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

So you make a filter with Where , then select the information you want to get - I kicked it CustomerBalance - and finally get the first result of the generated sequence (even if it already has only one element, anyway you want an element and not a sequence containing an element, which are very different data).

The likely generated internal query will look something like this:

SELECT TOP 1 CustomerBalance FROM Table WHERE AccountCurrentAdvisorId = @accountCurrentAdvisorId
    
11.04.2015 / 06:12
4

I would do so:

public decimal GetCustomerBalance(long accountCurrentAdvisorId) {
    return (from table in this.Table where table.AccountCurrentAdvisorId == accountCurrentAdvisorId select table).First();
}
    
15.04.2015 / 16:31
2

Null is returned because you are comparing a LONG with INT, try doing it that way.

public decimal GetCustomerBalance(int accountCurrentAdvisorId)
{
    return this.Table.Where(x => x.AccountCurrentAdvisorId == accountCurrentAdvisorId)
                 .Select(x => x.AccountCurrentAdvisorId).FirstOrDefault();
}
    
19.05.2015 / 00:45