user2977985
user2977985

Reputation:

Select count in linq to sql using a stored procedure

I want a count of the rows for the particular value

My .cs page code is

var rr_sel_cat = db.selcategories(Convert.ToInt32(8)).ToList();   //store procedure                
string count = Convert.ToString(rr_sel_cat.Count());

My stored procedure:

ALTER PROCEDURE dbo.selcategories
@subid int
AS
select count(*) from editor_j_inf where sub_h_a=@subid
RETURN

Ny table editor_j_inf has a column sub_h_a with values 1,2,3,4,6,8,9

When I used to pass a value "58" which is not present in sub_h_a

var rr_sel_cat = db.selcategories(Convert.ToInt32(58)).ToList();

it returns count of 1, and if I used to pass value "8" which is present in sub_h_a

var rr_sel_cat = db.selcategories(Convert.ToInt32(8)).ToList();

it also returns a count of 1

What's the problem?

Upvotes: 0

Views: 1371

Answers (4)

Vaibhav Parmar
Vaibhav Parmar

Reputation: 643

you can replace by the following Linq:

int sub_id=8;
from s in editor_j_inf where sub_h_a=subid
select s.count();

Upvotes: 0

Thomas
Thomas

Reputation: 5921

Try:

var rr_sel_cat = db.selcategories(Convert.ToInt32(8)).ToList();   //store procedure                
string count = Convert.ToString(rr_sel_cat.FirstOrDefault());

Because db.selcategories return a count, the return List should be with one element witch is already the count. It is why the number of element of your list is always 1.

Or just remove the ToList :

string count = db.selcategories(Convert.ToInt32(8)).ToString();

Upvotes: 1

Damith
Damith

Reputation: 63065

check the value of db.selcategories(Convert.ToInt32(8)) you don't need ToList and count here

var rowCount = db.selcategories(Convert.ToInt32(8));

Upvotes: 1

Andrew
Andrew

Reputation: 2335

Your SP returns the count, which is a single value hence value is 1. You either need

ALTER PROCEDURE dbo.selcategories
@subid int
AS
select * from editor_j_inf where sub_h_a=@subid
RETURN

or simply get the value back from the SP and that will be your count

Upvotes: 1

Related Questions