1.list轉換為DataTable(如果有需要)
public static DataTable ListToDataTable<T>(List<T> entitys) { //檢查實體集合不能為空 if (entitys == null || entitys.Count < 1) { throw new Exception("需轉換的集合為空"); } //取出第一個實體的所有Propertie Type entityType = entitys[0].GetType(); PropertyInfo[] entityProperties = entityType.GetProperties(); //生成DataTable的structure //生產代碼中,應將生成的DataTable結構Cache起來,此處略 DataTable dt = new DataTable(); for (int i = 0; i < entityProperties.Length; i++) { //dt.Columns.Add(entityProperties[i].Name, entityProperties[i].PropertyType); dt.Columns.Add(entityProperties[i].Name); } //將所有entity添加到DataTable中 foreach (object entity in entitys) { //檢查所有的的實體都為同一類型 if (entity.GetType() != entityType) { throw new Exception("要轉換的集合元素類型不一致"); } object[] entityValues = new object[entityProperties.Length]; for (int i = 0; i < entityProperties.Length; i++) { entityValues[i] = entityProperties[i].GetValue(entity, null); } dt.Rows.Add(entityValues); } return dt; }
2.得到DATATable
DataTable CutLayHdDt = ListToDataTable(CutLayHds);//CutLayHds is list
3.數據庫創建 自定義類型
創建的自定義類型與表類型,字段需和C#datatable 的列名一致
CREATE TYPE [dbo].[CUT_LAY_HDCustomType] AS TABLE( [LAY_TRANS_ID] [bigint] NULL, [LAY_ID] [bigint] NULL, [SIZE_CD] [nvarchar](20) NOT NULL, [RATIO] [int] NOT NULL, [SIZE_CD2] [nvarchar](20) NULL, [JOB_ORDER_NO] [nvarchar](20) NULL, [LAY_NO] [bigint] NULL ) GO
4.編寫存儲過程進行使用
create proc USP_CUTTING_TATABLET_PULL_FINISH2 ( @CutlayhdList CUT_LAY_HDCustomType READONLY--定義參數,接收datatable ) as SELECT *, IDENTITY(int, 1, 1) AS ID INTO #cutlayhdtemp FROM @CutlayhdList--將參數的值插入到臨時表
5.C#調用
SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter() { ParameterName = "CutlayhdList", Value = CutLayHdDt };//值為上面轉換的datatable
ExecuteNonQuery("USP_CUTTING_TATABLET_PULL_FINISH", parameters);
-------------方法
public static void ExecuteNonQuery(string spName, SqlParameter[] parameterValues) { string connectionString = ConfigurationManager.ConnectionStrings["CuttingDev"].ConnectionString; using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); // Invoke RegionUpdate Procedure SqlCommand cmd = new SqlCommand(spName, conn); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 0; foreach (SqlParameter p in parameterValues) { //eck for derived output value with no value assigned if ((p.Direction == ParameterDirection.InputOutput) && (p.Value == null)) { p.Value = DBNull.Value; } cmd.Parameters.Add(p); } cmd.ExecuteNonQuery(); } }