获取子记录列表
本文关键字:列表 记录 获取 | 更新日期: 2023-09-27 18:18:50
我有一个数据库,看起来像这样:
tbl_Seminar
ID
isActive
tbl_SeminarFees
ID
seminar_id -- foreign key
fee_text
我想获得所有正在进行的研讨会(isActive ==1)以及与该研讨会相关的费用列表。每个研讨会在tbl_SeminarFees中可以有n条记录,作为其费用。我能够返回一个linq结构,它返回一个对象列表,看起来像这样{seminar, SeminarFee}
但我想创建一个嵌套结构,看起来像这样:
{seminar, List<SeminarFee>}
我的linq查询应该是什么样子?
这是我当前的linq:
var results = from s in context.Seminar
join p in context.SeminarFees on
s.ID equals p.SeminarID
where s.IsActive == 1
select new
{
Seminar = s,
Fees = p
};
我如何更改这个以获得这些列表:{seminar, List<SeminarFee>}
@lazyberezovsky给了我一个好主意,使用组连接和到另一个变量。但是我怎么循环遍历结果集呢。下面是我现在的代码:
foreach (var seminarAndItsFeesObject in results)
{
//do something with the seminar object
//do something with the list of fees
}
然而,这会给我以下错误:
Argument type 'SeminarFees' does not match the
corresponding member type
'System.Collections.Generic.IEnumerable`1[SeminarFees]'
我做错了什么?
谢谢
您可以使用group join将基于键相等的内部序列项分组(也称为join..into)以获得与研讨会相关的所有费用:
var results = from s in context.Seminar
join f in context.SeminarFees on
s.ID equals f.SeminarID into fees // here
where s.IsActive == 1
select new
{
Seminar = s,
Fees = fees
};
服务器端不能调用ToList()
。但是您可以稍后在客户端上映射结果。
BTW您可以在Seminar
对象上定义导航属性Fees
:
public virtual ICollection<SeminarFee> Fees { get; set; }
在这种情况下,您将能够加载研讨会与费用:
var results = context.Seminar.Include(s => s.Fees) // eager loading
.Where(s => s.IsActive == 1);
var results = from s in context.Seminar
join p in context.SeminarFees on s.ID equals p.SeminarID
where s.IsActive == 1
group p by s into grouped
select new {
Seminar = grouped.Key,
Fees = grouped.ToList()
};