linq group query into my mvc model - c#

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!

You need to select g.Key.
g is an IGrouping<CustomerModel, Purchase> that includes the elements in the group.

Related

how to get the max value of id from second table using join in entity framework in asp.net c#

I have two tables, from 1st table i want to get all records and from 2nd table i want the max id value of that record. I am using entity framework in asp.net c#.
i tried the below code but it takes only single record from first table i.e tblblogs. and leave all the records, how to get all those records by using this query? plz help me out I'll be very grateful to you. Thanks !
var query= (from c in db.tblBlogs join a in db.tblBlogMedias on c.id
equals a.BlogId where c.id==db.tblBlogMedias.Max(p=>p.id)
select new
{}
If I understood, you want to get an object with specific fields of Blogs and a list of tblBlogMedias.
You could try this code:
var query2 = (from c in db.tblBlogs
orderby c.Id descending
group c.tblBlogMedias by new { c.Id, c.Name } into gb //It will show Id and name of tblBlogs, you can use more fields if you want
select new {
Id = gb.Key.Id,
Name = gb.Key.Name, //I don't know if you have this field, but you should change it
SecondTable = gb.ToList()
})
.OrderByDescending(o => o.Id) //this orderby with FirstOrDefault() replace where c.id==db.tblBlogMedias.Max(p=>p.id)
.FirstOrDefault();

Selecting the whole data after joining in linq

When I need to join some tables using linq, and when those tables consist of a lot of fields, it takes a lot of work to get all the data that I need. For instance:
var result = from i in Person
join y in Works
on i.PID euqals y.PID
join z in Groups
on y.GID on z.GID
select new {Name = i.Name, Work = y.work, WG = z.GroupName};
How can make the query return all the tables ?
I guess what you need is simply this :
var Query = from x in Table_1
join y in Table_2
on x.id equals y.id
where x.Country.Equals("X Country")
select new {x,y};

Grouping a many relationship in LINQ

I've got the following code:
var preGroup =
from l in e.WorkOrderRequests
join w in e.WorkOrders on l.WorkOrderRequestKey equals w.WorkOrderRequestKey into lw
from l2 in lw.DefaultIfEmpty()
select new { l.WorkOrderRequestStatusKey,
l.WorkOrderRequest_Status.Status,
w.Property.Address.StateKey,
w.Property.Address.MetroKey };
The relationship structure is that a Work Order Request can have many Work Orders, so it is a 1 to many relationship. I want to do a select so that each work order request will show up for as many times as there are work orders attached to it. But also it still should appear if there are no work orders attached. So a left outer join makes sense. The select above doesn't work, but that shows the data that I want to select. I need to then group this data:
var workOrderRequests =
(from l in preGroup.ToList()
group l by new { l.WorkOrderRequestStatusKey, l.Status, l.StateKey, l.MetroKey } into g
select new DashboardView
{
StatusKey = g.Key.WorkOrderRequestStatusKey,
StatusName = g.Key.Status,
StateKey = g.Key.StateKey,
MetroKey = g.Key.MetroKey,
Count = g.Count()
});
I can't get to the grouping because my preGroup query is not working. I have been able to accomplish this for other things, but those are all 1 to 1 relationships. Any help is much appreciated.

Fetch top N rows of the table in Entity Framework

I'm kind of stuck with a problem that I'm having.
Among others, I have this tables in my DB:
Product (int productId, ...otherProductInfo)
Customer (int customerId, ...otherCustomerInfo)
SoldToData ( int productId, int customerId)
I want to get top ten selling products using Entity Framework in MVC2. How can I do that?
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Following thekip's and Pr0fess0rX's advices, this is what I have done so far, and it seems to be working:
using (Entities db = new Entities())
{
var groupedProducts = (from p in db.Products
join s in db.SoldToData
on p.productId equals s.productId
group p by p.id
into ProductGroup
orderby ProductGroup.Count() descending
select ProductGroup).Take(10).ToList();
List<Products> products = new List<Products>();
products.AddRange(groupedProducts.Select(gp => gp.First()));
}
Is this the proper way?
If you have an IQueryable to query the datasource you could use orderby etc for ordering followed by Take(10)?
Join both products and customer
Group them and get the count of products per customer
Order descending by the count.
Take top 10 of the times
Get the name of the result products (top 10)

LINQ aggregate across more than one table

I want to replicate this query in LINQ to SQL but am too unfamiliar with how to do it.
SELECT A.Recruiter, SUM(O.SaleAmount * I.Commission) --This sum from fields in two different tables is what I don't know how to replicate
FROM Orders AS O
INNER JOIN Affiliate A ON O.AffiliateID = A.AffiliateID
INNER JOIN Items AS I ON O.ItemID = I.ItemID
GROUP BY A.Recruiter
I've got this far:
from order in ctx.Orders
join item in ctx.Items on order.ItemI == item.ItemID
join affiliate in ctx.Affiliates on order.AffiliateID == affiliate.AffiliateID
group order //can I only group one table here?
by affiliate.Recruiter into mygroup
select new { Recruiter = mygroup.Key, Commission = mygroup.Sum(record => record.SaleAmount * ?????) };
group new {order, item} by affiliate.Recruiter into mygroup
select new {
Recruiter = mygroup.Key,
Commission = mygroup
.Sum(x => x.order.SaleAmount * x.item.Commission)
};
And an alternative way of writing the query:
from aff in ctx.Affiliates
where aff.orders.Any(order => order.Items.Any())
select new {
Recruiter = aff.Recruiter,
Commission = (
from order in aff.orders
from item in order.Items
select item.Commission * order.SaleAmount
).Sum()
};
try linqpad, just Google, amazing tool!

Categories