Linq Sum Columns including joins - c#

I have two tables.
[Table.Game]
Columns are "PK_id" "username" and "couponID"
[Table.Coupons]
Columns are "PK_id" "CouponID" and "Points"
The two columns "CouponID" are associated with eachother. Let say i have two rows with the user "harry" in [Table.Game] this person has two different couponID.
In [Table.Coupons] this user "harry" has "CouponID" 1 and 2. Column "Points" have 10 and 20.
To the question how do u sum this two different point values that have different "CouponIDs". This does work if i have only one "CouponId". But not when the user has 2 different CouponIDs. Values is 0
var points = (from p in linq.Coupons
join g in linq.games on p.couponID equals g.couponID
where g.username == username && g.couponID == p.couponID
select (int)p.win).Sum();

you already join the tables on the CouponID don't need it in the where:
var points = (
from p in linq.Coupons
join g in linq.games on p.couponID equals g.couponID
where g.username == username
select (int)p.win).Sum();

I solved the problem by using single to many relations instead of many to many in my database.

Related

group by linq to entity query to get one record having latest timestamp by joining tables

There are two tables and using linq query to get records. From second table, there can be multiple rows corresponding to first table with date timestamp... based on below query, I am getting all records, but is there a way we can get the row from second table which has latest timestamp ?
Table Parent
ID Name
1 M
2 N
3 O
4 P
5 Q
Table Child
Id fkID DateTime
1 2 01/12/2021 09:12:20
2 2 01/12/2021 09:13:20
3 2 01/12/2021 09:14:20
4 2 01/12/2021 09:15:20
5 2 01/12/2021 **09:16:20**
Linq query:
from p in Parent
join c in Child on p.id equals c.fkId into cJoin
from cJoin in cJoin.DefaultIfEmpty()
select new TempResponse
{
Id = p.Id,
Name = p.Name,
Date = c.Date
}
I am getting 10 records using above query but just need 5 records i.e. from child table instead of all 5 records, we need a record that has latest time stamp
**expected output**
1 M
2 N 01/12/2021 09:16:20
this record is 5'th record from child table because this one has latest date time stamp
( latest record )
3 O
4 P
5 Q
Is there any way we can use group by and get the record that has latest time stamp from second table ?
Assuming you have defined navigation properties for the FK, I would use a query like;
dbContext.Child.Where(c => c.Date == c.Parent.Child.Max(c2 => c2.Date))
I believe you can use:
var ans = from p in Parent
join cmax in (
from c in Child
group c by c.fkId into cg
select cg.OrderByDescending(c => c.Date).FirstOrDefault())
on p.Id equals cmax.fkId into cJoin
from c in cJoin.DefaultIfEmpty()
select new TempResponse {
Id = p.Id,
Name = p.Name,
Date = c != null ? c.Date : null
};
Note that the order of results seems to vary on SQL Server unless you add another orderby clause before the select to force an order.

Selecting a new object without grouping in linq?

I am trying to write a query to collect the Job number, start date, customer name, Model, and completion date for jobs at my work. To get this info, I look at 3 different tables, using joins to put them together. Here are the three tables:
STAGE - (stages each job goes through during production)
ORDER - (this is where I get the customer's name)
JOBS (start date, completion date, job number, model)
So most of the info is from the JOBS table. But I'm joining onto the ORDER table by Job Number (JobNum) to obtain the customer's name. Here's what the query looks like. I created it in SQL before I tried to translate it into one of my ViewModels:
var CompletedTrucksQuery =
(from FA in context.JOBS
join ORD in context.ORDER on FA.ORGANIZATION_ID equals ORD.ORGANIZATION_ID
where FA.ORDER_NUMBER == ORD.ORDER_NUMBER
join StageF in context.STAGE on FA.JobNum equals StageF.JobNum
where StageF.StageID == 325
join TruckComp in context.STAGE on FA.JobNum equals TruckComp.JobNum
where TruckComp.StageID == 327
join INSP in context.STAGE on FA.JobNum equals INSP.JobNum
where INSP.StageID == 487
orderby StageF.CompDate descending, FA.JobNum ascending
select new {FA.JobNum, FA.StartDate, ORD.CUSTOMER_NAME, FA.MODEL_NAME, StageF.CompDate});
At this point, I'm wanting to select the
Job number (from JOBS),
the start date, (From JOBS),
the Customer's name (from ORDER),
the Model of product (from JOBS),
and the date it was completed in StageF (from STAGE)
as you can see in my select statement. I DO have an object to hold each of these called CompJob, and have tried to do a 'group by' and select a new CompJob and set the properties, but I can't seem to group it right and get 'access' to all of the properties I want to set. Here's an excerpt of what I'm talking about:
group new {FA.JobNum, O = ORD} by StageF into grp
select new CompletedTruck
{
JobNum = grp.Key.JobNum,
StartDate = grp. //???
}
As you can tell I stopped, because for some reason I couldn't 'find' the start date. I know it's something to do with my grouping. I'm very new to linq and databases, in general.
MY QUESTION: What's the best way I can select these columns of interest into my
ObservableCollection<CompJob> CompJobList;
so that I may use it in my scrollviewer in a view?
Thanks to everyone for helping me out. I solved the issue and this is what I did. I followed Gert Arnold's suggestion of selecting a new CompJob object. This would set each row of the query to a new object:
select new CompJob {JobNum = FA.JobNum, StartDate = FA.StartDate, Customer = ORD.CUSTOMER_NAME,.....}
and then said
).ToList();
At the end of the query. Then I set my ObservableCollection to the list returned by my query:
CompJobList = CompletedTrucksQuery ;
Thanks again for helping me out; I know I'm new to all of this!

How to use group by on an outer join in linq to SQL

Please i have my two tables, i recently learnt to outer join the two in linq. My problem now is i want to use group by a particular column for a i want to return a sum as well. Below is how i join the tables.
var result = from l1 in repository.Locations
join l2 in repository.Rooms on l1.LocationName equals l2.Location
into l3
from tempLocations in l3.DefaultIfEmpty()
select new
{
l1.LocationName,
total = (tempLocations == null ? String.Empty : tempLocations.Location)
};
My problem is the column total, intend to group by l1.LocationName and the count() as total. Please any help would be appreciated.
UPDATE
I want to group by the Location Column and LocationName column from the l1 and l2 tables. I want to return something like.
The LocationNAme is from Locations Table , LOcation Column is from Rooms Table , i want to outer join the two tables where LocationNAme = Location and count existence of LocationName in Room Table .

How to compare/match values in sql server in two different tables

I need to have two tables.
First table (tblStudent) has fields student_id,firstname,lastname,class,rollno.
Second table(feeType) has fields class,admissionFee, tuitionFee etc.
I want to show the different fee for each class.
Like class 5 pays 600 as tuition fee where as class 6 will pay 700.
Eg. If class is 5 in first table then only the class 5 row in feeType should be shown ? How do I design tables as such? How do I join two tables? I will be using sql server 2008 and c# as frontend. Thanks from a novice.
This is the simplest type of INNER JOIN:
SELECT *
FROM tblStudent AS s
INNER JOIN feeType as f ON s.class = f.class
Your INNER JOIN would only return matching records,for non-matching records you could use a FULL JOIN and WHERE criteria to check.
SELECT *
FROM tblStudent AS s
INNER JOIN feeType as f ON s.class = f.class where s.class=null;
Visit here
This will list all the class names and their fees.
SELECT
s.class,
f.admissionFee as admission_fee,
f.tuitionFee as tuition_fee
FROM
tblStudent as s
JOIN feeType as f ON s.class = f.class
GROUP BY
s.class;
I hope this will help you to get the exact result set.

Linq To Entity - Filter Relational Data Problem

I have 2 tables.
Table 1 and Table 2. They have one to many relation. I'm trying to do a query like below. It works fine with finding the result. I mean if it cannot find any result according to the params i got null value as usual. However it brings all Table 2 results all the time in Table 1 class and I do want to get only Table 2 results according to the query.
dc.Table1s.SingleOrDefault(t1 => t1.SearchField1 == param1
&& t1.Table2s.Any(t2 => t2.SearchField2 == param2
&& t2.SearchField3 == param3));
I do want the result as Table1 class and filtered with Table1.Table2s. Is it possible???
You need to define the how you want the relationship between the two tables to be used.
For instance, if Table 2 has a reference to Table 1, and Table 1 has a collection of table 2:
var result = (from t1 in Table1s
from t2 in t1.Table2s // this leverages the relationship
where t1.sf1 == p1
&& t2.sf2 = p2
&& t2.sf3 == p3
select t1).FirstOrDefault();
The above will join the two using your relationship and give you all t1's that match the criteria.

Categories

Resources