问题
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