1

Linq DataContext を使用してデータベースからデータ リストを取得中に問題に直面しています

次のコードを試しています

public class DBContextNew : DataContext {

    public static string StoreProcedureName = "";

    [Function(Name = StoreProcedureName, IsComposable = false)]
    public ISingleResult<T> getCustomerAll()
    {

        IExecuteResult objResult =
          this.ExecuteMethodCall(this, (MethodInfo)(MethodInfo.GetCurrentMethod()));

        ISingleResult<T> objresults =
            (ISingleResult<T>)objResult.ReturnValue;
        return objresults;
    }


}

しかし、エラーが発生しています

[関数 (名前 = StoreProcedureName、IsComposable = false)]

as 属性引数は、定数式、typeof 式、または属性パラメーター型の配列作成式でなければなりません

実行時に Name 属性に値を渡したいと思いました。

出来ますか?

助けてください。

4

3 に答える 3

0

問題は:

 public static string StoreProcedureName = "";

定数にする必要があります。

public const string StoreProcedureName = "";

コンパイラは、エラー メッセージでこれを通知します (これは定数式でなければなりません)。

于 2013-07-04T09:25:51.777 に答える
0

単純な属性では、代わりに城のダイナミック プロキシを使用します。属性でそれを行うと、実行時にリフレクションを使用して属性パラメーターの何かを変更する必要があるためです。このように、user1908061アドバイスのように、2 つの問題が発生します。

1) パフォーマンスの問題。実行時にストアド プロシージャを呼び出すことは、アプリケーションのパフォーマンスにとって非常に「重く」なります 2) マルチスレッドの問題。2 つのスレッドが 10 ティックの間隔でこのコードを呼び出すとします。

var method = typeof(TestClass).GetMethod("Foo");
var attribute = method.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute;
attribute.Bar = "Hello";

Thread1 はBarparam の属性を「Hello」に変更しますが、このときに Thread2 が同じコードにアクセスし、Barparam を別の値に変更すると、問題が発生します。タイムラインで見てみましょう。

 0 ticks - Thread1 started to work, accessed the property of TestAttribute and made the Bar param = "Hello"
 20 ticks - Thread2 started to work, accessed the property of TestAttribute and made the Bar param = "SomeOtherValue"
 40 ticks - You are expecting that you will call function with `Bar`=="Hello", but it's getting called with the `Bar`=="SomeOtherValue"
 60 ticks - Thread2 getting called with `Bar`=="SomeOtherValue"

そのため、Thread1 は間違った結果を取得します。

そのため、CastleDynamicProxy を使用して必要なことを行うことをお勧めします。これを使用すると、メソッドの前にいくつかのコードを実行してメソッドの結果を置き換えることができ、メソッドの後にいくつかのコードを実行することもできます。この方法は実行時に機能します。

また、テクノロジーもあります。PostSharp は同じことを行いますが、少し別の方法で行います。これはコンパイル時に機能します。

于 2013-07-04T10:51:35.923 に答える
0

残念ながら、動的な値 (変数の内容など) を属性宣言に提供することはできません。

ただし、実行時に属性の値を変更できます。

public class TestAttribute : Attribute
{ public string Bar { get; set; } }

public class TestClass
{
    [Test]
    public string Foo()
    { return string.Empty; }
}

次に、この値を変更します。

var method = typeof(TestClass).GetMethod("Foo");
var attribute = method.GetCustomAttribute(typeof(TestAttribute)) as TestAttribute;
attribute.Bar = "Hello";

属性はクラスのすべてのインスタンスで共有されることに注意してください。

于 2013-07-04T10:05:31.907 に答える