Reputation: 3
Is this following a good practice or not?
cmd.CommandText = "StoredProcedureName_InsertUserDetails"; //Is this line a good or bad since Sql injection is possible here.
cmd.Parameters.Add(new SqlParameter("@name",SqlDbType.VarChar)).Value=name;
cmd.Parameters.Add(new SqlParameter("@age",SqlDbType.Int)).Value=age;
Upvotes: 0
Views: 270
Reputation: 3009
Here is your code with added Commandtype
:
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "StoredProcedureName_InsertUserDetails"; // This line is ok
cmd.Parameters.Add(new SqlParameter("@name",SqlDbType.VarChar)).Value=name;
cmd.Parameters.Add(new SqlParameter("@age",SqlDbType.Int)).Value=age;
Is it good practice to execute a stored procedure by writing it as a string?
What could go wrong?
CommandText
as hard-coded string as shown above, there is no possibility to SQL Injection attack.If your Stored procedure inserts only single UserDetails
entity, you can also make use of Entity Framework. This article shows how to map entity CUD (Create, Update, Delete) operations to Stored Procedures automatically by calling MapToStoredProcedures()
in Fluent API. Article also explains how you can map your own custom Stored Procedures to your EF Entities.
Upvotes: 1