cod*_*ior 2 c# linq sql-server asp.net linq-to-sql
我是C#和Linq-to-Sql的新手.
我有一个这种形式的表'InstrumentTypes':
typeId(int) | type(varchar) | subttype(varchar)
101 Keys keyboard
102 Keys accessories
103 Guitar acoustic
104 Guitar electric
Run Code Online (Sandbox Code Playgroud)
我需要根据'type'搜索作为输入从表中获取所有'typeId',并且所有typeId都需要绑定到ASP Repeater.
到目前为止,我已经编写了以下代码:
// 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
}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚如何迭代查询结果,将它们存储在数据结构中并将它们绑定到Repeater.
以下代码将其绑定到Repeater:
Repeater1.DataSource= //name of data structure used to store the types goes here
Repeater1.DataBind();
Run Code Online (Sandbox Code Playgroud)
有人可以帮帮我吗?
编辑:对于获得的每个typeID,我想访问另一个表'Instruments'并检索属于该typeId的所有Instruments.表'仪器'是这样的:
instrumentId typeID name description
1000 101 yamaha xyz
Run Code Online (Sandbox Code Playgroud)
根据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();
Run Code Online (Sandbox Code Playgroud)
但是我得到一个编译错误,说"列表中最好的重载方法匹配有一些无效的参数".我哪里错了?
你得到了什么
var type = (from m in database.InstrumentTypes
where m.type == requestType
select m);
Run Code Online (Sandbox Code Playgroud)
是一个集合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);
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松转换为
var ids = (from m in database.InstrumentTypes
where m.type == requestType
select m.Id).ToList();
Run Code Online (Sandbox Code Playgroud)
[编辑]
只要您定义了InstrumentType和之间的关系,您就可以直接查询仪器并导航到相关对象Instrument.
var instruments = (from i in database.Instrument
where i.InstrumentType.type == requestType
select i);
Run Code Online (Sandbox Code Playgroud)
无需单独的foreaches或查询.在i.InstrumentType将转换为join,因为你可以用SQL事件探查器验证
| 归档时间: |
|
| 查看次数: |
26510 次 |
| 最近记录: |