.net - .Net 中的反射可以通过查看用户定义的类型名称来帮助动态构建表值参数/SqlMetaData [] 对象吗?

标签 .net sql reflection table-valued-parameters

我已经开始在 Sql Server 2k8 中使用表值参数进行批处理操作。我非常喜欢这个功能,感觉它是在漫长的等待之后才出现的。

但是,为了从 .Net 代码中传递 TVP,构建 SQLMetaData[] 并在循环中填充值需要付出太多的努力。

如何避免在同步中维护 .Net 代码中的 Sql Server 和 SQLMetaData[] 对象中的用户定义类型?
当我在 SQL 中更改类型定义时,没有简单的方法知道我在 .Net 的庞大代码中在哪里使用了该类型。

.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)
    {

    }
}

现在,如果您的表有 100 列,想象一下您的代码。

最佳答案

您可以使用反射来做到这一点。首先,必须有一种方法可以覆盖名称和长度的默认值。为此,请定义 Attribute年代:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class LengthAttribute : Attribute
{
    private readonly int m_length;
    public int Length
    {
        get { return m_length; }
    }

    public LengthAttribute(int length)
    {
        m_length = length;
    }
}

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
class ColumnNameAttribute : Attribute
{
    private readonly string m_name;
    public string Name
    {
        get { return m_name; }
    }

    public ColumnNameAttribute(string name)
    {
        m_name = name;
    }
}

并在您的类型上使用它们:

class TradingRuleMetadata
{
    public Guid ID { get; set; }

    public string Name { get; set; }

    [Length(-1)]
    public string Description { get; set; }

    public bool Enabled { get; set; }

    public string Category { get; set; }

    public string Custom1 { get; set; }

    public string Custom2 { get; set; }

    public string Custom3 { get; set; }

    [Length(20)]
    public string CreatedBy { get; set; }

    [ColumnName("CreatedTS")]
    public DateTime CreatedDate { get; set; }

    [Length(20)]
    public string ModifiedBy { get; set; }

    [ColumnName("ModifiedTS")]
    public DateTime ModifiedDate { get; set; }

    public bool IsFactory { get; set; }
}

然后,您可以创建一个方法,将这种类型的集合映射到 SqlDataRecord 的集合。 :

private static readonly Dictionary<Type, SqlDbType> SqlDbTypes =
    new Dictionary<Type, SqlDbType>
    {
        { typeof(Guid), SqlDbType.UniqueIdentifier },
        { typeof(string), SqlDbType.VarChar },
        { typeof(bool), SqlDbType.Bit },
        { typeof(DateTime), SqlDbType.DateTime }
    };

static IList<SqlDataRecord> GetDataRecords<T>(IEnumerable<T> data)
{
    Type type = typeof(T);

    var properties = type.GetProperties();

    SqlMetaData[] metaData = new SqlMetaData[properties.Length];
    try
    {
        for (int i = 0; i < properties.Length; i++)
        {
            var property = properties[i];

            string name = property.Name;
            var columnNameAttribute = GetAttribute<ColumnNameAttribute>(property);
            if (columnNameAttribute != null)
                name = columnNameAttribute.Name;

            var dbType = SqlDbTypes[property.PropertyType];

            if (dbType == SqlDbType.VarChar)
            {
                int length = 255;

                var lengthAttribute = GetAttribute<LengthAttribute>(property);
                if (lengthAttribute != null)
                    length = lengthAttribute.Length;

                metaData[i] = new SqlMetaData(name, dbType, length);
            }
            else
                metaData[i] = new SqlMetaData(name, dbType);
        }
    }
    catch (Exception ex)
    {
        throw new Exception();
    }

    var records = new List<SqlDataRecord>();
    foreach (T item in data)
    {
        SqlDataRecord record = new SqlDataRecord(metaData);
        try
        {
            var values = properties.Select(p => p.GetValue(item, null)).ToArray();
            record.SetValues(values);
            records.Add(record);
        }
        catch (Exception ex)
        {

        }
    }
    return records;
}

static T GetAttribute<T>(PropertyInfo property)
{
    return (T)property.GetCustomAttributes(typeof(T), true).SingleOrDefault();
}

这段代码使用了很多反射,所以对你来说可能太慢了。如果是这种情况,您将需要实现某种缓存。一种方法是创建 Expression完成所有这些工作,然后将其编译为委托(delegate)(仅限.Net 4,因为您需要 BlockExpression )。

此外,您的实际要求可能更复杂,因为您可能需要忽略某些属性或类似的东西。但这应该很容易添加。

关于.net - .Net 中的反射可以通过查看用户定义的类型名称来帮助动态构建表值参数/SqlMetaData [] 对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126372/

相关文章:

c# - C# 中的复数

sql - nvarchar 中有多少个可用字符(MAX)

sql - 使用动态列创建表

ruby - Ruby 中的内省(introspection)

c# - 从字典中填充一个类

c# - 我应该做哪些事情来创建高性能且健壮的反射缓存?

c# - c#中的if语句性能

c# - 无法在 .NET(完整)4.5 控制台应用程序中加载 Rosyln 生成的 PCL 程序集

c# - PayPal SDK 未预填充的账单字段

mysql - 优化mysql子查询语句