Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does SqlCommandBuilder.GetUpdateCommand() need to be called before using SqlDataAdpater.Update()?

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?

like image 757
Scott Chamberlain Avatar asked Jun 25 '10 15:06

Scott Chamberlain


1 Answers

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 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.

like image 166
jsmith Avatar answered Oct 18 '22 01:10

jsmith