Diver Dan
Diver Dan

Reputation: 9963

linq group query into my mvc model

I have 2 tables within my EF4 project. They dont have a join.

CustomerTable CustomerId ConsumerName AllowEmails

PurchaseTable PurchaseId CustomerId PurchaseDate ......

What I am trying to do is return a grouped Customer when they have transactions within the PurchaseTable. If they haven't made any purchases or consumer Id isn't yet added to the CustomerId I want to ignore them.

I have a linq query that is working like I want

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

Now I could just do a foreach loop and add the results into a list however I think it would be nice to add to the list as part of the query.

This is what I have got so far.

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

Can anyone point me in the right direction to fix my query?

Thanks for your help!

Upvotes: 2

Views: 750

Answers (1)

SLaks
SLaks

Reputation: 887225

You need to select g.Key.

g is an IGrouping<CustomerModel, Purchase> that includes the elements in the group.

Upvotes: 1

Related Questions