普通的ADO.NET獲取DataSet的寫法如下: using System.Configuration; using System.Data; using System.Data.SqlClient; public class SQLHelper { private static readonly ...
普通的ADO.NET獲取DataSet的寫法如下:
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;
}
}
}
View Code
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Default" connectionString="Data Source=.;Initial Catalog=EFDb;Integrated Security=true"/>
</connectionStrings>
</configuration>
View Code
這裡需要獲取DataTable的主鍵信息,調試時發現沒有主鍵信息,而實際資料庫中是有主鍵(Id)
此時需要給SqlDataAdapter設置屬性MissingSchemaAction為System.Data.MissingSchemaAction.AddWithKey
修改後的SQLHelper為
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;
}
}
}