0

I have list object of type my class(Employee) and it has around 3 items.

Let's say for example:

empObj.Id = 3, empObj.Name = abc, emp.Value = Yes
empObj.Id = 4, empObj.Name = xyz, emp.Value = No
empObj.Id = 5, empObj.Name = pqr, emp.Value = Yes

Now, I want to insert all the items as individual rows into my DB using a stored procedure.

I don't want to hit the DB for each item.

My input parameter for SaveMethod in my data layer will be the above list object and my approach is like following:

Public Overridable Function SaveMethod(businessEntity As List(Of Employee)) As Boolean
    Using scope As System.Transactions.TransactionScope = New System.Transactions.TransactionScope()
        'DECLARE CONNECTION VARIABLE
        Dim objSqlConn As SqlConnection = Nothing
        'DECLARE SQL PARAMS VARIABLE
        Dim objSqlParams As SqlParameter() = Nothing
        'DECLARE BOOLEAN VARIABLE
        Dim bolReturnValue As Boolean = False
        'SET THE CONNECTION
        objSqlConn = GetCSSConnection()
        'SET THE PARAMETERS TO THE STORED PROCEDURE
        objSqlParams = New SqlParameter(3) {}
        For i As Integer = 0 To businessEntity.Count - 1
            objSqlParams(0) = New SqlParameter("@myParam1", SqlDbType.Int)
            objSqlParams(0).Value = 2 ' businessEntity(i).Id

            objSqlParams(1) = New SqlParameter("@myParam2", SqlDbType.Int)
            objSqlParams(1).Value = businessEntity(i).Name

            objSqlParams(2) = New SqlParameter("@myParam3", SqlDbType.Bit)
            objSqlParams(2).Value = businessEntity(i).value
        Next

        'BUILD NEW SQL CONNECTION AND EXECUTE THE STORED PROCEDURE
        'ASSIGN THE RESULT TO BOOLEAN VARIABLE
        bolReturnValue = (Microsoft.VisualBasic.IIf(ExecuteNonQuery(objSqlConn, CommandType.StoredProcedure, "myStoredProcedure", objSqlParams) > 0, True, False))

        CloseConnection(objSqlConn)
        Return bolReturnValue 'RETURNS BOOLEAN VALUE
    End Using
End Function

It's not throwing any error, it is returning True as well. But it's not saved to the database.

What is missing here? Is this approach correct? Is there any better way?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Santosh
  • 2,355
  • 10
  • 41
  • 64

2 Answers2

0

Why don't you go with table-valued parameter, which available with SQL server 2008.

0

Before End Using you need to complete your transaction to apply changes:

scope.Complete()
Amc
  • 88
  • 7