views:

21

answers:

1

When I use a SqlCommandBuilder to push updates/inserts/deletes to the server do I need to call .GetUpdateCommand(), .GetInsertCommand(), and .GetDeleteCommand()?

using (var adapter = new SqlDataAdapter("select * from MyTable", _connection))
using (var builder = new SqlCommandBuilder(adapter))
{
    adapter.Fill(dt);

    //Magic happens        

    builder.GetUpdateCommand(); //is this line necessary
    builder.GetInsertCommand(); //is this line necessary
    adapter.Update(dt);
}

I have seen conflicting examples on what is the correct procedure to do. I know it works without it but I did not know if it did something special behind the scenes. Is this necessary or is it cargo cult programming?

+2  A: 

I did some testing on my test database to see if I could come up with a scenario where an error would occur if I did NOT call GetInsertCommand(). It turns out it can happen, in my case, it happened when I was updating several different tables within a database.

For some reason when updating my 4th table it could not insert correctly. This troubled me, so I decided to do a little more research, which brought me here. Pay close attention to:

"After the Transact-SQL statement is first generated, the application must explicitly call RefreshSchema if it changes the statement in any way. Otherwise, the GetInsertCommand will still be using information from the previous statement, which might not be correct."

This tells me that it CAN work work without calling it, but it's better to call it. I tried to find reasoning for why sometimes it does work, and sometimes it doesn't. But I have not been able to figure it out completely.

jsmith
Do do not NEED to set them, I was wondering why some examples do. (I ran my code without calling the get commands and it updated my server fine.)
Scott Chamberlain