3

デバッグでコードを実行すると、次のエラーが発生します。

文字列から一意識別子への変換時に変換に失敗しました

コードは次のとおりです。

public class UserObject
{
    private string m_name = string.Empty;

    public UserObject(string id)
    {
    #region Internal Logic
        try
        {
            using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
            {
                string sSQL = "SELECT [UserName] FROM [aspnet_users] WHERE [UserID] = @UserID";
                using (SqlCommand cm = new SqlCommand(sSQL, cn))
                {
                    cm.Parameters.AddWithValue("@UserID", id);
                    cn.Open();
                    using (SqlDataReader rd = cm.ExecuteReader())
                    {
                        while (rd.Read())
                        {
                            m_name = rd[0].ToString();
                        }
                        rd.Close();
                    }
                    cn.Close();
                }
            }
        }
        catch (Exception ex)
        {

        }
    #endregion Internal logic
    }
}
4

1 に答える 1

4

idメソッドに渡されるときに値がないという質問へのコメントで、あなたは言いました。データベースの観点からは、uniqueidentifiers はnull( DBNullC# では) にすることができますが、これを実現するには、パラメーターを省略するか、DBNull.Value明示的に設定する必要があります。

C# ではGuid使用できないため、 への呼び出しで、または に変換できる文字列を指定nullする必要があります。Guid.EmptyGuidAddWithValue

EDITサンプル コードは次のとおりです。使用する SQL ステートメントを考えると、ユーザー ID に s のみが含まれている場合を除き
、ケースの結果は得られないことに注意してください。SQL ステートメントの句を次のように変更することをお勧めします。Guid.Empty0where

WHERE [UserId] = ISNULL(@UserID, [UserId])

そうすれば、 を渡すとすべてのユーザーを取得できますnull

public UserObject(string id)
{
    try
    {
        using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
        {
            string sSQL = "SELECT [UserName] FROM [aspnet_users] WHERE [UserID] = @UserID";
            using (SqlCommand cm = new SqlCommand(sSQL, cn))
            {

                if (id.Length == 0)
                    cm.Parameters.AddWithValue("@UserID", Guid.Empty);
                else if (id == null)
                    cm.Parameters.AddWithValue("@UserID", DBNull.Value);
                else
                    cm.Parameters.AddWithValue("@UserID", Guid.Parse(id));

                cn.Open();
                using (SqlDataReader rd = cm.ExecuteReader())
                {
                    while (rd.Read())
                    {
                        m_name = rd[0].ToString();
                    }
                    rd.Close();
                }
                cn.Close();
            }
        }
    }
    catch (Exception ex)
    {

    }
于 2012-05-11T11:52:04.503 に答える