2

我是 C# 和 Linq-to-Sql 的新手。

我有一个这种形式的表'InstrumentTypes':

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

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

我需要根据“类型”作为输入的搜索从表中获取所有“类型 ID”,并且所有类型 ID 都需要绑定到 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,我想访问另一个表“仪器”并检索属于该 typeId 的所有仪器。表“仪器”是这样的:

instrumentId     typeID    name     description
1000             101       yamaha   xyz

根据 Arialdo 的回答,我正在这样做:

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);

无需单独的foreaches 或查询。将i.InstrumentType转换为 a join,您可以使用 SQL 探查器进行验证

于 2012-04-16T07:52:46.077 回答
3

I am not sure what you are asking.

With out explicitly defining the returned type of your query you are already returning an IEnumerable<InstrumentTypes> object. If you want a list of ID's you can simply refine your query to return ID's rather than a list of InstrumentTypes. Of course, then you'd be returning an IEnumerable<int> object.

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