What does MissingSchemaAction.AddWithKey really do?

风格不统一 提交于 2019-12-11 12:36:57

问题


The default value of SqlDataAdapter.MissingSchemaAction is MissingSchemaAction.Add, but when I specify the AddWithKey I can't understand what it really do ?

System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter();
da.MissingSchemaAction = MissingSchemaAction.AddWithKey;

DataSet ds = new DataSet();
da.Fill(ds, "mytable");

When the use of AddWithKey can be useful ?


回答1:


Documentation here says, it "adds the necessary columns and primary key information to complete the schema"

It states the primary function of AddWithKey as: "This ensures that incoming records that match existing records are updated instead of appended."

A little reverse engineering reveals the following:

When you invoke DbDataAdapter.Fill(DataSet, string) it executes the DbCommand.ExecuteReader with CommandBehavior set to SequentialAccess

If you specify MissingSchemaAction = MissingSchemaAction.AddWithKey; the CommandBehavior.KeyInfo is added to the behavior.

This causes the DbCommand.ExecuteReader invoked internally to add the following on top of your query:

SET NO_BROWSETABLE ON;

Which is documented here by Microsoft (as below)

The browse mode lets you scan the rows in your SQL Server table and update the data in your table one row at a time. To access a SQL Server table in your application in the browse mode, you must use one of the following two options:

The SELECT statement that you use to access the data from your SQL Server table must end with the keywords FOR BROWSE. When you turn on the FOR BROWSE option to use browse mode, temporary tables are created.

You must run the following Transact-SQL statement to turn on the browse mode by using the NO_BROWSETABLE option:

SET NO_BROWSETABLE ON

When you turn on the NO_BROWSETABLE option, all the SELECT statements behave as if the FOR BROWSE option is appended to the statements. However, the NO_BROWSETABLE option does not create the temporary tables that the FOR BROWSE option generally uses to send the results to your application.



来源:https://stackoverflow.com/questions/33641549/what-does-missingschemaaction-addwithkey-really-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!