开发者

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

When I use a SqlCommandBuilder to push updates/inserts/deletes to the serv开发者_C百科er 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜