tags:

views:

28

answers:

1

Hi!

I need to execute SQL query with output parameter.

For example,

 SELECT @Count = COUNT(*) FROM dbo.SomeTable
 SELECT * FROM SomeTable WHERE Id BETWEEN 1 AND 10

After quering I need to know the @Count value. How can I do it with LINQ without using a stored procedure?

Thank you.

+1  A: 
int value = yourDB.SomeTable.Count(q=>q.id >=1 && q.id <= 10);

linq is pretty easy :)


edit: so you want 2 items, the count, and then a limited part of the array.

        List<SomeTable> li = yourDB.SomeTable.ToList();
        int number = li.Count;
        List<SomeTable> partial = li.GetRange(0, 10);

or

        int value = yourDB.SomeTable.Count();
        List<SomeTable> partial = yourDB.SomeTable.ToList().GetRange(0, 10);

so the best LINQ thing for paging is:

        List<SomeTable> partial = yourDB.SomeTable.OrderBy(q=>q.id).Skip(0).Take(10).ToList();
Stefanvds
I understand, what you mean, but I have to implement paging. It is much more complex than I wroteSELECT * FROM SomeTable WHERE Id BETWEEN 1 AND 10Is there a way to execute clean T-SQL code with output parameter?
SuperX
+1, this is the colution. 1 and 10 could be int vars.
Jonathan
Using your solution solution I have to do 2 queries to DB, but I want to male only one.
SuperX
and what is the reason you want to make life difficult by swearing with only 1 query?
Stefanvds
@SuperX: your two statements still result in two queries, even if you only use one execute statement in C#.
Ruben
@Stefanvds: Are you sure you mean `yourDB.SomeTable.ToList().GetRange(0, 10)`? That would load the entire table into memory! Shouldn't you use `yourDB.SomeTable.Where(q=>q.id >=1 or perhaps `yourDB.SomeTable.OrderBy(q=>q.id).Take(10).ToList()`
Ruben
yes ruben, that's a better solution, especially the last one.
Stefanvds
there i fixed it :)
Stefanvds