Reputation: 543
If I create a
SqlDataAdapter adapterSales = new SqlDataAdapter (mySelectCommand, connString)
and then I create the insert command for the adapter lets say
adapterSales.InsertCommand = new SqlCommand (myInsertCommand);
Why do I need to pass another connection to the last constructor? I mean if I already passed the connection string why the adapter doesn't work with that to create the sql connection that I'm going to be working with?
Upvotes: 0
Views: 604
Reputation: 15861
as MSDN states it SqlDataAdapter
the InsertCommand can be generated automatically if you set the SelectCommand property and use the SqlCommandBuilder.
When InsertCommand is assigned to a previously created SqlCommand, the SqlCommand is not cloned. The InsertCommand maintains a reference to the previously created SqlCommand object.
Ecah command object, associated with connection, so every time it needs info about the command object to perform operation.
Upvotes: 0
Reputation: 41252
It is the command objects (select, insert, update, delete) that need the connection. The data adapter itself doesn't actually have a specific connection directly associated with it. Using Reflector, I see that the following are the members of SqlDataAdapter
(no connection object directly in it):
// Fields
private SqlCommandSet _commandSet;
private SqlCommand _deleteCommand;
private SqlCommand _insertCommand;
private SqlCommand _selectCommand;
private int _updateBatchSize;
private SqlCommand _updateCommand;
private static readonly object EventRowUpdated;
private static readonly object EventRowUpdating;
So, in theory, you could use a different connection with each command associated with the data adapter, but it is not obvious that there would be many uses for that scenario (maybe dealing with two database where one is read only and updates are sent to the other).
Upvotes: 1
Reputation: 14874
It's the parameter needed by SqlCommand
constructor, AFAIR InsertCommand
could be created automatically from select command then you don't need this duplication even for defining the InsertCommand
.
From MSDN
if primary key information is present in the DataSet, the InsertCommand can be generated automatically if you set the SelectCommand property and use the SqlCommandBuilder.
Upvotes: 0