Question

I am trying to retrieve the curent users UserId from the membership provider but something does not go the way I planned it to.Here is my code:

cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "forum_GetUsernameId";
cmd.Parameters.Add("@username" , user);
var data = cmd.ExecuteScalar();

 @username nvarchar 
   AS
 SELECT UserId
 FROM aspnet_Users
 WHERE UserName = @username

While debugging I noticed that data returns null witch can not be posible unless ExecuteScalar() is not the method I should be calling. Also user gets set to the curent username of that I am certain.

What am I doing wrong here?

Was it helpful?

Solution

If you're using SqlMemberShipProvider anyway it's simple:

Guid userID = (Guid) Membership.GetUser().ProviderUserKey; 

OTHER TIPS

You are using SqlCommand.Parameter.Add() method in your code. If you are using Add() method with two arguments, you have two choices;

Add(string, SqlDbType);
Add(string, object);

enter image description here

In this case, I think you are tried to use first Add() one. So, when I look in the database, UserId is a uniquidentifier.

enter image description here

Because of that, you should change your code to;

cmd.Parameters.Add("@username", SqlDbType.UniqueIdentifier);

There is nothing wrong to use ExecuteScalar() in your code. It returns first row of first column on your query. So, your query returns only one column with one row, there is no problem. But, ExecuteScalar() returns an object, maybe you might need convert to string with .ToString().

If you are using SqlMembershipProvider, do what Tim said.

Otherwise, I don't think you should be using ExecuteScalar() to read a data from a field/column, try using ExecuteReader:

var data = cmd.ExecuteReader();
while(reader.Read())
{
 //code goes here
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top