SqlDataAdapter.FillSchema(DataTable)方法填充数据表的主键和约束
自动填充主键和约束有两种方法:
1. adp.MissingSchemaAction = MissingSchemaAction.AddWithKey
2. dt1 = adp.FillSchema(data, SchemaType.Mapped);//填充结构
public class FillDataWithSchema
{
private SqlConnection _Connection = null;
public FillDataWithSchema()
{
string S = @"Server=.\SQLExpress;Database=D:\MY SOURCECODE\CSHARP\CSFRAMEWORKTESTDB\CSFrameworkTestDB.MDF;Integrated Security=True;";
_Connection = new SqlConnection(S);
}
public void FillData()
{
DataTable data = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM tb_MyUser", _Connection);
adp.Fill(data);//填充数据
ShowSchema(data);//显示结构
//AddWithKey: 自动填充数据表结构,如:主键和限制
//预设值Add,不填充结构
adp.MissingSchemaAction = MissingSchemaAction.AddWithKey;//Default Value is: Add
adp.Fill(data);//填充数据和结构,如:主键和限制
ShowSchema(data);//显示结构
DataTable dt1;
dt1 = adp.FillSchema(data, SchemaType.Mapped);//填充结构
ShowSchema(dt1);//显示结构
_Connection.Close();
Console.ReadLine();
}
/// <summary>
/// 显示表结构
/// </summary>
/// <param name="data"></param>
private void ShowSchema(DataTable data)
{
Console.WriteLine("Rows:" + data.Rows.Count);
//主键
Console.WriteLine("PrimaryKey:" + data.PrimaryKey.Length.ToString());
foreach (DataColumn c in data.PrimaryKey)
Console.WriteLine(c.ColumnName);
//约束
Console.WriteLine("Constraints:" + data.Constraints.Count.ToString());
foreach (Constraint c in data.Constraints)
Console.WriteLine(c.ConstraintName);
//无法获取主外键主联定义
Console.WriteLine("ParentRelations:" + data.ParentRelations.Count.ToString());
Console.WriteLine("ChildRelations:" + data.ChildRelations.Count.ToString());
Console.WriteLine("------------------------------------------------");
}
}
//来源:C/S框架网(www.csframework.com) QQ:1980854898