c# – How to use DataAdapter to fill only DataTable structure without data?

Question:

A DataAdapter is passed to my class from outside, I need to use it to fill only the structure (columns with data types) DataTable without data. The following code, contrary to my expectations, pulls in all the data that the SelectCommand can return.

public class myclass
{
    private readonly DataAdapter da;
    private DataSet ds;
    public myclass (DataAdapter da)
    {
        this.ds = new DataSet();
        this.da = da;
        var dt = ds.Tables.Add("MyTable");
        da.Fill(0, 0, dt);            
    }    
}

metadata on used Fill

 // // Сводка: // Добавляет или обновляет строки в объекте System.Data.DataTable для получения // соответствия строкам в источнике данных, начиная с указанной записи и вплоть // до заданного максимального количества получаемых записей. // Параметры: // startRecord: // Номер записи (с нуля), с которой необходимо начать. // // maxRecords: // Максимальное число извлекаемых записей. // // dataTables: // Объект System.Data.DataTable для заполнения из источника данных.

In what way can only the structure in the DataTable be filled?

Answer:

As pointed out in the comment, the MSDN article contains a description of how to do this.

var dataAdapter = ....
var dataTable = new DataTable();
dataAdapter.FillSchema(dataTable, SchemaType.Mapped)

If the DbDataAdapter object DbDataAdapter created with a description of the parameters of the relationship between tables and columns (mapping) using the TableMappings property of the DbDataAdapter , then when SchemaType.Mapped is SchemaType.Mapped , the source data schema attempts to supplement the DataTable object's schema with missing columns based on the data returned by the SelectCommand. If you want to accept only data and ignore the communication parameters defined for TableMapping, then you should use SchemaType.Source

Scroll to Top