I’m working on a C# application where I need to pass a value from an enum to a SQL Server stored procedure, but the database expects a string input, not an integer. I’m using Enum.GetName
to convert the enum value to its corresponding string representation, but when I try to execute my code, Enum.GetName
returns null, and I receive the following error:
System.Data.SqlClient.SqlParameterCollection.ValidateType(Object value)
at System.Data.SqlClient.SqlParameterCollection.Add(Object value)
at FMAdminServices.Dtos.Response.McqSettingRepository.GetMcqCollaboratorsSettingbycollab(String role, Int32 trainingtype)
Here is my enum definition and relevant code:
public enum TrainingTypes
{
Onboarding = 1,
Aptitude = 2,
Interview = 3,
Active = 4
}
public async Task<ApiResponse<List<GetMcqCollabGlobalSettingsResponse>>> GetMcqCollaboratorsSettingbycollab(string role, int trainingtype)
{
SqlConnection con = null;
SqlCommand cmd = null;
SqlDataReader reader = null;
try
{
con = new SqlConnection(_configuration.GetConnectionString("ConnStr"));
cmd = new SqlCommand("GetMCQGlobalSettings", con)
{
CommandType = CommandType.StoredProcedure
};
await con.OpenAsync();
cmd.Parameters.Add(new SqlParameter("@roleId", SqlDbType.VarChar, 100) { Value = role });
// Get the string representation of the enum value
string trainingTypeText = Enum.GetName(typeof(TrainingTypes), trainingtype);
// Add the trainingtype parameter as a string to the database
cmd.Parameters.Add(new SqlParameter("@trainingtype", SqlDbType.VarChar, 100) { Value = trainingTypeText });
// Execute stored procedure and read data...
// other part of code..
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (con != null)
{
await con.CloseAsync();
}
}
}
Despite passing a valid int value for trainingtype (e.g., 2), Enum.GetName is returning null when it should return “Aptitude”. This is causing issues when adding the parameter to the SQL command.
What I’ve Tried:
Ensuring that the value of trainingtype
passed in the method matches the enum values.
Debugging shows that the trainingtype has a valid value, but Enum.GetName is still returning null, hence trainingTypeText
returning null.
Why is Enum.GetName
returning null, and how can I fix this to properly pass the string representation of the enum to the stored procedure?
Thanks.
8