2

私はC#とLinq-to-Sqlを初めて使用します。

この形式のテーブル「InstrumentTypes」があります。

typeId(int)  | type(varchar)  |  subttype(varchar)

101               Keys           keyboard
102               Keys           accessories
103               Guitar         acoustic
104               Guitar         electric

入力として「type」による検索に基づいてテーブルからすべての「typeId」をフェッチする必要があり、すべてのtypeIdをASPリピーターにバインドする必要があります。

これまでのところ、次のコードを記述しました。

// requestType contains the type from the search
var type = (from m in database.InstrumentTypes
            where m.type == requestType
            select m);
foreach(var typeId in type)
{
    //code
}

クエリの結果を反復処理してデータ構造に格納し、リピーターにバインドする方法を理解できません。

次のコードは、それをリピーターにバインドします。

Repeater1.DataSource= //name of data structure used to store the types goes here
Repeater1.DataBind();

誰か助けてくれませんか?

編集:取得したtypeIDごとに、別のテーブル「Instruments」にアクセスして、そのtypeIdに属するすべてのInstrumentsを取得したいと思います。テーブル「Instruments」は次のようになります。

instrumentId     typeID    name     description
1000             101       yamaha   xyz

アリアルドの答えに基づいて、私はこれを行っています:

var type = (from m in database.InstrumentTypes
                          where m.type == requestType
                          select m);
            var instruments = new List<Instrument>();
            foreach (var i in type)
            {
                instruments.Add(from x in database.Instruments
                                where x.typeId == i.typeId
                                select x);
            }
            Repeater1.DataSource = instruments;
            Repeater1.DataBind();

しかし、「リストに最適なオーバーロードされたメソッドの一致にはいくつかの無効な引数があります」というコンパイルエラーが発生します。どこが間違っているのですか?

4

2 に答える 2

7

あなたが得るもの

var type = (from m in database.InstrumentTypes
        where m.type == requestType
        select m);

InstrumentTypesはのコレクションであり、IDのコレクションではありません。

これは私のために働く

var types = (from m in database.InstrumentTypes
        where m.type == requestType
        select m);
var ids = new List<int>();
foreach (var type in types)
{
    ids.Add(type.Id);
}

簡単に変換できます

var ids = (from m in database.InstrumentTypes
        where m.type == requestType
        select m.Id).ToList();

[編集]

InstrumentTypeとの間の関係を定義している限り、機器に直接クエリを実行して、関連するオブジェクトに移動できますInstrument

var instruments = (from i in database.Instrument
                      where i.InstrumentType.type == requestType
                      select i);

foreach個別のesやクエリを用意する必要はありません。SQLプロファイラーで確認できるように、i.InstrumentTypeはに変換されますjoin

于 2012-04-16T07:52:46.077 に答える
3

あなたが何を求めているのかわかりません。

返されるクエリのタイプを明示的に定義しないと、すでにIEnumerable<InstrumentTypes>オブジェクトが返されます。IDのリストが必要な場合は、InstrumentTypesのリストではなく、IDを返すようにクエリを調整するだけです。もちろん、IEnumerable<int>オブジェクトを返すことになります。

var type = (from m in database.InstrumentTypes
        where m.type == requestType
        select m.typeId);
于 2012-04-16T08:07:58.193 に答える