Thursday, March 29, 2012

MissingSchemaAction question

I came across this code

PublicFunction GetCustomers()As DataSet

Dim custDAAs SqlDataAdapter =New SqlDataAdapter("SELECT CustomerID, CompanyName FROM Customers", nwindConn)

Dim custDSAs DataSet =New DataSet()

custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey

custDA.Fill(custDS, "Customers")

GetCustomers = custDS

EndFunction

The function seems simple enough. It just passes a dataset back to the caller. I understand every single line of code except for:
custDA.MissingSchemaAction = MissingSchemaAction.AddWithKey
What is this line of code for? and why is it needed? Seems to me you can write the function without it.

From the docs:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatamissingschemaactionclasstopic.asp
MissingSchemaAction specifies the action to take when adding data tothe DataSet and the required DataTable or DataColumn is missing. TheAddWithKey option adds the necessary columns and primary keyinformation to complete the schema.

Thanks for responding.
However why is it needed in the code above. Doesn't the 'FILL' command fill in the schema information into the Dataset. Would this function not work if the 'MissingSchemaAction' line of code was taken away?
TheFill method of theDataAdapter fills aDataSet only with table columns and rows from a data source; though constraints are commonly set by the data source, theFill method does not add this schema information to theDataSet by default. To populate aDataSet with existing primary key constraint information from a data source, you can either call theFillSchema method of theDataAdapter, or set theMissingSchemaAction property of theDataAdapter toAddWithKey before callingFill. This will ensure that primary key constraints in theDataSetreflect those at the data source. Foreign key constraint information isnot included and will need to be created explicitly, as shown inAdding Constraints to a Table.

0 comments:

Post a Comment