ADO.NET Get the data (dataset) and get the schema instance of the table at the same time

Time:2020-7-16

ordinary ADO.NET Write the dataset as follows:


using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public class SQLHelper
{
 private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
 public static DataSet GetDataSet(string sql)
 {
  using (SqlConnection conn =new SqlConnection(ConnectionString))
  {
   SqlCommand cmd = new SqlCommand(sql, conn);
   SqlDataAdapter adapter = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   conn.Open();
   adapter.Fill(ds);
   return ds;
  }
 }
}

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <connectionStrings>
 <add name="Default" connectionString="Data Source=.;Initial Catalog=EFDb;Integrated Security=true"/>
 </connectionStrings>
</configuration>

Here we need to get the primary key information of datatable. During debugging, it is found that there is no primary key information, but there is a primary key (ID) in the actual database

At this time, you need to set the attribute missingschemaaction to System.Data.MissingSchemaAction .AddWithKey

The modified sqlhelper is


using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public class SQLHelper
{
 private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
 public static DataSet GetDataSet(string sql)
 {
  using (SqlConnection conn =new SqlConnection(ConnectionString))
  {
   SqlCommand cmd = new SqlCommand(sql, conn);
   SqlDataAdapter adapter = new SqlDataAdapter(cmd);
   adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
   DataSet ds = new DataSet();
   conn.Open();
   adapter.Fill(ds);
   return ds;
  }
 }
}

The above article ADO.NET Getting the data (dataset) and getting the schema instance of the table is the whole content shared by Xiaobian. I hope it can give you a reference, and I hope you can support developeppaer more.