-1

I am trying to get the current userid from the parameter and to check if it exists in a Database Table using stored procedure

public PartialViewResult AllStates(string state, string userid)
{

    SqlCommand cmd = new SqlCommand();
    Following following = new Following();
    cmd.Parameters.Add("@userid", SqlDbType.BigInt).Value = userid;
    List<Farmer> model = db.Farmer.Where(u => u.FarmState == state).Take(3).ToList();
    var modelfollow = db.Following.SqlQuery("[dbo].[SelectFollow]").ToList();
    ViewBag.folo = modelfollow;
    return PartialView("_UsersList", model );
}

This is my stored Procedure

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE SelectFollow 
    @userid INT
AS
BEGIN
DECLARE @HasFollowed BIT
    IF EXISTS(SELECT * FROM dbo.Followings Where UserId = @userid)
BEGIN
SET @HasFollowed = 1
END
ELSE
BEGIN
SET @HasFollowed = 0
END
END
GO

Is there any thing I'm doing wrong?

Favour Emmanuel
  • 111
  • 3
  • 11

1 Answers1

0

The problem is in this line, which doesn't include any stored procedure (SP) parameter while the SP requires one parameter, hence the exception mentioned in the title has thrown:

var modelfollow = db.Following.SqlQuery("[dbo].[SelectFollow]").ToList();

Also you're adding parameter to SqlCommand instance which contains empty query string (and you're not execute it afterwards):

SqlCommand cmd = new SqlCommand();
cmd.Parameters.Add("@userid", SqlDbType.BigInt).Value = userid;

Since you're using DbSet.SqlQuery() method, you may pass query parameter(s) as second parameter of that method by declaring SqlParameter instance:

public PartialViewResult AllStates(string state, string userid)
{
    // define stored procedure parameter here
    var parameter = new SqlParameter("@userid", SqlDbType.BigInt);
    parameter.Value = userid;

    List<Farmer> model = db.Farmer.Where(u => u.FarmState == state).Take(3).ToList();

    // use stored procedure parameter declared above
    var modelfollow = db.Following.SqlQuery("[dbo].[SelectFollow] @userid", parameter).ToList();
    ViewBag.folo = modelfollow;
    return PartialView("_UsersList", model);
}
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
  • If you have another problem, just create a new question by linking to this one. Also you may consider to read [this](https://stackoverflow.com/help/someone-answers) if the provided answer deemed helpful. – Tetsuya Yamamoto Mar 11 '19 at 11:51
  • Ok, but how do i link a question to this one – Favour Emmanuel Mar 11 '19 at 12:49
  • Please help me how do i come out of this "You have reached your question limit Sorry, we are no longer accepting questions from this account. See the Help Center to learn more." – Favour Emmanuel Apr 19 '19 at 11:12