Vermajai1995
Vermajai1995

Reputation: 3

Is it good practice to execute a stored procedure by writing it as a string?

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

Answers (1)

Risto M
Risto M

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?

  • SQL Injection? When you set CommandText as hard-coded string as shown above, there is no possibility to SQL Injection attack.
  • Stored procedure name not sync with calling code: You can get run-time exceptions if calling code refers to unknown stored proc.
    • Keep your stored procedure creation scripts under version control, near to your code which uses it. This way it is possible to keep stored procedure in sync with C# code.
    • Automatic tests can be created to notice if Stored Proc has breaking changes

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

Related Questions