net MVC 3存储过程从表中返回一个值

本文关键字:一个 返回 MVC 存储过程 net | 更新日期: 2023-09-27 18:00:35

我有要返回的SQL:

  CREATE PROCEDURE [Zinc].[GetUserByEmail]
    @Email nvarchar (256)
  AS
    SELECT zu.UserId FROM zinc.users zu WHERE zu.Email = @Email

到目前为止,在我的存储库中我有:

public int GetUserByEmail(string email)
{
    using (SqlConnection conn = new SqlConnection(ZincModelContainer.CONNECTIONSTRING))
    {
        using (SqlCommand cmd = conn.CreateCommand())
        {
            conn.Open();
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.CommandText = "[Zinc].[GetUserByEmail]";
            //not sure how to go from here?
        }
        return userId;
    }
}

net MVC 3存储过程从表中返回一个值

由于它是标量值,请使用:

cmd.Parameters.Add("@Email", SqlDbType.NChar).Value = email;
var UserId = cmd.ExecuteScalar();
cmd.Parameters.Add("@Email", SqlDbType.NChar).Value = email;
int UserId = cmd.ExecuteScalar();

Microsoft文档通常是最好的起点。请参阅:http://msdn.microsoft.com/en-us/library/877h0y3a.aspx以获取从SqlConnection读取的示例。