5

バッチ操作のために Sql Server 2k8 でテーブル値パラメーターの使用を開始しました。私はこの機能がとても気に入り、長い間待っていたように感じます.

ただし、.Net コードから TVP を渡すには、SQLMetaData[] を構築し、ループ内で値を埋めるために多大な労力が必要です。

Sql Server でユーザー定義型を保持し、同期の .Net コードで 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 列ある場合、コードを想像してみてください。

4

2 に答える 2

3

リフレクションを使用してそれを行うことができます。まず、名前と長さのデフォルト値をオーバーライドする方法が必要です。Attributeこれを行うには、 sを定義します。

[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();
}

このコードは非常に多くのリフレクションを使用しているため、遅すぎる可能性があります。その場合は、何らかのキャッシュを実装する必要があります。これを行う 1 つの方法は、Expressionこのすべての作業を行う を作成し、それをデリゲートにコンパイルすることです (.Net 4 のみ、必要になるためBlockExpression)。

また、実際の要件は、一部のプロパティや類似のものを無視する必要がある場合があるため、より複雑になる場合があります。しかし、それは簡単に追加できるはずです。

于 2011-08-20T14:01:11.867 に答える
0

質問にはコードサンプルを提供するのに十分ではありませんが、このようなものについては、別の.NET実行可能ファイルを作成してSQLメタデータを読み取り、各UDTのヘルパークラス(あなたの例によく似ています)を生成するようなことをします. コード生成の利点は、実行時の速度が少し速いことと、さらに重要なことに、ソース コードを手書きの場合と同じように読み取ってステップ実行できることです。それは特に難しいことでもありません - 特に今は partial キーワードが存在するからです。

于 2011-08-20T00:31:48.317 に答える