vin*_*ani 5 .net sql reflection table-valued-parameters
我已经开始在Sql Server 2k8中使用表值参数进行批处理操作.我很喜欢这个功能,感觉经过漫长的等待.
但是,为了从.Net代码传递TVP,构造SQLMetaData []然后在循环中填充值需要花费太多精力.
如何避免在同步中保留.Net代码中的Sql Server和SQLMetaData []对象中的用户定义类型?当我在SQL中更改类型定义时,没有简单的方法可以知道我在.Net的大量代码中使用该类型的所有内容.
Can .Net Reflection可以通过提供用户定义类型的名称来拯救程序员构建SQLMetadata,并通过提供对象数组来帮助填充数据.
考虑这个例子:
SqlMetaData[] tvp_TradingAllocationRule = new SqlMetaData[13];
try
{
tvp_TradingAllocationRule[0] = new SqlMetaData("ID", SqlDbType.UniqueIdentifier);
tvp_TradingAllocationRule[1] = new SqlMetaData("Name", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[2] = new SqlMetaData("Description", SqlDbType.VarChar, -1);
tvp_TradingAllocationRule[3] = new SqlMetaData("Enabled", SqlDbType.Bit);
tvp_TradingAllocationRule[4] = new SqlMetaData("Category", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[5] = new SqlMetaData("Custom1", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[6] = new SqlMetaData("Custom2", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[7] = new SqlMetaData("Custom3", SqlDbType.VarChar, 255);
tvp_TradingAllocationRule[8] = new SqlMetaData("CreatedBy", SqlDbType.VarChar, 20);
tvp_TradingAllocationRule[9] = new SqlMetaData("CreatedTS", SqlDbType.DateTime);
tvp_TradingAllocationRule[10] = new SqlMetaData("ModifiedBy", SqlDbType.VarChar, 20);
tvp_TradingAllocationRule[11] = new SqlMetaData("ModifiedTS", SqlDbType.DateTime);
tvp_TradingAllocationRule[12] = new SqlMetaData("IsFactory", SqlDbType.Bit);
}
catch (Exception ex)
{
throw new Exception("Error Defining the tvp_TradingActionCondition in .Net" + ex.Message);
}
foreach (TradingRuleMetadata ruleMetadata in updatedRules)
{
SqlDataRecord tradingAllocationRule = new SqlDataRecord(tvp_TradingAllocationRule);
try
{
tradingAllocationRule.SetGuid(0, ruleMetadata.ID);
tradingAllocationRule.SetString(1, ruleMetadata.Name);
tradingAllocationRule.SetString(2, ruleMetadata.Description);
tradingAllocationRule.SetBoolean(3, ruleMetadata.Enabled);
tradingAllocationRule.SetString(4, ruleMetadata.Category);
tradingAllocationRule.SetString(5, ruleMetadata.Custom1);
tradingAllocationRule.SetString(6, ruleMetadata.Custom2);
tradingAllocationRule.SetString(7, ruleMetadata.Custom3);
tradingAllocationRule.SetString(8, ruleMetadata.CreatedBy);
tradingAllocationRule.SetDateTime(9, ruleMetadata.CreatedDate);
tradingAllocationRule.SetString(10, ruleMetadata.ModifiedBy);
tradingAllocationRule.SetDateTime(11, ruleMetadata.ModifiedDate);
tradingAllocationRule.SetBoolean(12, ruleMetadata.IsFactory);
tvp_TradingAllocationRuleRecords.Add(tradingAllocationRule);
}
catch (Exception ex)
{
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果您的表有100列,请想象您的代码.
问题中没有足够的代码示例,但对于类似的事情,我会做一些事情,比如编写一个单独的 .NET 可执行文件来读取 SQL 元数据并为每个 UDT 生成帮助器类(看起来很像您的示例)。代码生成的优点是运行时速度更快,更重要的是,您可以像手写一样阅读和单步执行源代码。这也不是特别难——尤其是现在partial 关键字存在。