operator not defined for System.Data.SqlClient.SqlConnection and System.Data.SqlClient.SqlConnection
i hope i'm just doing so开发者_JAVA百科mething wrong here. Ideally i'm trying to open the connection, open a transaction execute a ton of prebuilt sqlstatements (with parameters) against this connection then close the connection. ideally all in the same batch.
It's easy enough to wrap this all in a for loop, however i'd like to use the forEach function of the list generic to set the connection as it'll probably be faster than my implementation of calling List.Item(i) in the loop but i get some strange errors.
Dim sqlStatements As List(Of SqlCommand) = New List(Of SqlCommand)
Dim conn As SqlClient.SqlConnection = New SqlConnection("...")
sqlStatements.Item(0).Connection = conn
'Works
sqlStatements.ForEach(Function(ByRef cmd As SqlCommand) cmd.Connection = conn)
'ERROR: Operator '=' is not defined for types
'System.Data.SqlClient.SqlConnection'
'and 'System.Data.SqlClient.SqlConnection
What does this error really mean?
Just use a standard For Each
loop
For Each cmd In sqlStatements
cmd.Connection = conn
Next
The reason is that Function lambda's in VB.Net (at least for VB9) are required to return a value. The portion of the lambda that reads
cmd.Connection = conn
is doing a comparison and not an assignment.
This has changed in VB10 since they added statement lambdas:
sqlStatements.ForEach(Sub(cmd) cmd.Connection = conn)) '(my syntax may be off)
As a side note, why do you think the ForEach method would be faster than a conventional For Each loop? Have you actually run into a performance issue?
精彩评论