获取子记录列表

时间:2013-06-16 21:20:27

标签: c# linq linq-to-sql

我有一个如下所示的数据库:

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]'

我做错了什么?

由于

2 个答案:

答案 0 :(得分:6)

您可以使用group join根据密钥相等性(a.k.a. 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 您可以在Fees对象上定义navigation property Seminar

public virtual ICollection<SeminarFee> Fees { get; set; }

在这种情况下,您可以加载研讨会并收取费用:

var results = context.Seminar.Include(s => s.Fees) // eager loading
                     .Where(s => s.IsActive == 1);

答案 1 :(得分: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()
                };