Red Swan
Red Swan

Reputation: 15543

How to build Generic code for insert data into database using stored procedure?

So far I used to with ADO.NET code to insert the data into sql database/table using the stored procedure by mapping the stored procedure parameters with values. But is there any generic code which can fetch the parameters and their datatypes from provided stored procedure name, assign the values to parameters that we will provide and insert directly to table accordingly.? Any suggestions.

Upvotes: 0

Views: 559

Answers (1)

Mario Stopfer
Mario Stopfer

Reputation: 551

I have created a library (Generic Database Access) which can do exactly what you have described. You can either use the library itself, or just extract the code you need. But in short, my solution can provide you with the parameter names, assign values to the parameters, and execute the stored procedure, whose name you need to provide.

An example of how you would execute such an Insert command with a stored procedure which takes a single varchar parameter and inserts it into a table, is as follows:

new NonQuery<Student>(new Student() { Name = "Jimmy" });

Just be sure to type the "System.Data.SqlClient.SqlCommandBuilder" in the Builder TextBox in the helper application, or use the following XML setup in order to tell the library to derive the parameters from the stored procedure.

<Property>
  <Name>Builder</Name>
  <Assembly>System.Data.dll</Assembly>
  <Type>System.Data.SqlClient.SqlCommandBuilder</Type>
</Property>

Upvotes: 2

Related Questions