String DefaultDBConnection = "Data Source=111.111.0.111;Initial Catalog=ZMT;User ID=name;Password=pwd";//連接字符串
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(DefaultDBConnection))//開啟數據庫連接
{
SqlTransaction trans = null;
string orgCode = "1=1";
string SQL = string.Format(@"select * from instockplan where ISPID=559
select * from InStockPlanDetails where ISPID=559 and @test");
conn.Open();
trans = conn.BeginTransaction();//打開一個事物
SqlCommand cmd = new SqlCommand(SQL, conn);
cmd.Parameters.AddWithValue("@test", orgCode);
cmd.Transaction = trans;//此次操作綁定當前的事物
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(ds);//把查詢的數據存在ds
//var i = 0;
//foreach (var item in ds.Tables[0].Rows)
//{
// Console.WriteLine(i++);
//}
trans.Commit();//事物提交
conn.Close();//關閉數據庫連接
}
List<Plan> list = new List<Plan>();
foreach (DataRow item in ds.Tables[0].Rows)
{
Plan plan = new Plan();
Type planAttr = typeof(Plan); //獲取當前類屬性
System.Reflection.PropertyInfo[] planAttrs = planAttr.GetProperties();//獲取當前這個類的所有屬性
foreach (PropertyInfo attr in planAttrs)
{
if (ds.Tables[0].Columns.Contains(attr.Name))
attr.SetValue(plan, item[attr.Name].ToString(), null);//給當前plan對象賦值該字段
if (attr.Name == "planDetails"&& ds.Tables[1].Rows.Count>0)//如果子類里邊有數據的時候才進去
{
foreach (DataRow Pitem in ds.Tables[1].Rows)
{
PlanDetails planD = new PlanDetails();
Type planDAttr = typeof(PlanDetails);
System.Reflection.PropertyInfo[] planDAttrs = planDAttr.GetProperties();
foreach (var attrD in planDAttrs)
{
if (ds.Tables[1].Columns.Contains(attrD.Name))
attrD.SetValue(planD, Pitem[attrD.Name].ToString(), null);
}
plan.planDetails.Add(planD);
}
}
}
list.Add(plan);
}
foreach (var item in list)
{
Console.WriteLine(item.ISPID);
}