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

Asked

Viewed 175 times

11

I am trying to make a LINQ query in my BD SQL Server, but the result of it always comes 'null'. I need the first user ID I query.

This is the way I try to consult:

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

        return result;
    }

3 answers

10


You need to do this:

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

I put in the Github for future reference.

So you make a filter with the Where, then selects the information you want to pick up - I guessed it would be CustomerBalance - and finally takes the first result of the generated sequence (even if it already has only one element, after all you want an element and not a sequence containing an element, which are given very different).

To query probable internal generated will be something like this:

SELECT TOP 1 CustomerBalance FROM Table WHERE AccountCurrentAdvisorId = @accountCurrentAdvisorId
  • Thanks @bigown

5

I would do so:

public decimal GetCustomerBalance(long accountCurrentAdvisorId) {
    return (from table in this.Table where table.AccountCurrentAdvisorId == accountCurrentAdvisorId select table).First();
}

3

It is returned Null because you are comparing a LONG with INT, try to do it this way.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.