linq group查询到我的mvc模型

时间:2011-11-09 23:07:40

标签: c# linq asp.net-mvc-3

我的EF4项目中有2个表。他们没有联系。

CustomerTable的 顾客ID ConsumerName AllowEmails

PurchaseTable PurchaseId 顾客ID 购买日期 ......

我想要做的是返回一个分组客户,当他们在PurchaseTable中有交易时。如果他们尚未进行任何购买或消费者ID尚未添加到CustomerId,我想忽略它们。

我有一个像我想要的那样工作的linq查询

 var query = from t in ctx.PurchaseTable
                    join j in ctx.CustomerTable on t.CustomerId equals
                        j.ConsumerId
                        where j.AllowEmails==true
                    group t by new
                                   {
                                       t.CustomerId,
                                       j.ConsumerName,
                                       j.EmailAddress
                                   }
                    into g
                    select new {Customer = g.Key};

现在我可以做一个foreach循环并将结果添加到列表中但是我认为将其作为查询的一部分添加到列表中会很好。

这是我到目前为止所得到的。

  var data = (from t in ctx.PurchaseTable
                     join j in ctx.CustomerTable on t.CustomerId equals
                        j.CustomerId 
                    where j.AllowEmails== true
                    //group t by new //group t by new ConsumerModel
                    group t by new CustomerModel
                                   {
                                       CustomerName= t.CustomerName,
                                       Email= j.EmailAddress,
                                       CustomerId = j.CustomerId


                                   }
                    into g select g);

有人能指出我正确的方向来修复我的查询吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您需要select g.Key

g是一个IGrouping<CustomerModel, Purchase>,其中包含该组中的元素。