What is the equivalent of this SQL query in linq - c#

Select Distinct DVDTitle, CopyNumber from Actors a
inner join CastMembers b
on a.ActorNumber = b.ActorNumber
inner join DVDTitles c
on b.DVDNumber = c.DVDNumber
inner join DVDCopys d
on c.DVDNumber = d.DVDNumber;
How to write this sql query in linq:
So far I've done this which returns value twice:
var actorList = from a in _db.Actors
join b in _db.CastMembers
on a.ActorNumber equals b.ActorNumber
join c in _db.DVDTitles
on b.DVDNumber equals c.DVDNumber
join d in _db.DVDCopys
on c.DVDNumber equals d.DVDNumber
orderby c.DvdTitle
select new Actor
{
ActorNumber = a.ActorNumber,
ActorSurName = a.ActorSurName,
ActorFirstName = a.ActorFirstName,
DVDTitle = c.DvdTitle,
CopyNumber = d.CopyNumber
};
I've also tried:
var actorList_01 = actorList.Distinct();
but the result is same.

try this
var matchingList = actorList
.GroupBy(x => x.ActorNumber )
.Select(g => g.First())
.ToList();

Related

Selecting max in linq query or rewriting to method chain syntax

I managed to turn this SQL query:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount],
FROM [DbEfTesting].[dbo].[Cars] c
left join Accessories a on c.CarId = a.CarId
left join CarsPeople cp on cp.CarId = c.CarId
left join People p on cp.PersonId = p.PersonId
group by c.CarId, c.Codename
into a LINQ query:
var x = from c in _context.Cars
join a in _context.Accessories on c.CarId equals a.Car.CarId
join j in _context.CarsPeople on c.CarId equals j.CarId
join p in _context.People on j.PersonId equals p.PersonId
group c by new { c.CarId, c.Codename } into g
select new VMCarAggregate()
{
CarId = g.Key.CarId,
Codename = g.Key.Codename,
CarCount = g.Count()
};
But now I'm lost trying to include a max value e.g the SQL:
SELECT c.carId, c.Codename, count(c.CarId) as [CarCount], max(a.AccessoryId) ...
I googled it and found lots of answers for method syntax. If I were using method chain syntax, I know I could do something like this:
_context.Accessories.Max(a => a.AccessoryId);
but I can't figure out how to do the group by in method chain syntax so either:
How can I convert that query to method syntax?
or
How can I inject a select on the max a.AccessoryId in the LINQ query format?
Try the below code once:
var x = from c in _context.Cars
join a in _context.Accessories equals a.Car.CarId
join j in _context.CarsPeople on c.CarId equals j.CarId
join p in _context.People on j.PersonId equals p.PersonId
group new { c.CarId, c.Codename, a.AccesoryId } by new { c.CarId, c.Codename } into g
select new
{
CarId = g.Key.CarId,
Codename = g.Key.Codename,
CarCount = g.Count(),
MaxAccesory = g.Max(z => z.AccesoryId)
};

WHERE condition with SELECT, MAX statement using LINQ/Lambda

I am trying to convert below SQL query to LINQ/Lambda in C#
SELECT DISTINCT M.InternalID, P.Code
FROM (
dbo.MeasureValue MV
INNER JOIN dbo.Measure M ON MV.MeasureID = M.ID
INNER JOIN dbo.Provider P ON MV.ProviderID = P.ID
)
WHERE MV.ReportingDate = (
SELECT MAX(ReportingDate)
FROM (
SELECT ReportingDate
FROM dbo.MeasureValue
WHERE MeasureID = MV.MeasureID
) MaxReportingDate
);
I have got so far,
(from MV in MeasureValues
join M in Measures on MV.MeasureID equals M.ID
join P in Providers on MV.ProviderID equals P.ID
Where //???
select new //Distinct??
{ M.InternalID, P.Code} )
Could someone please guide me how to use nested WHERE condition as in SQL query and do MAX of nested SELECT and DISTINCT on whole?
As a whole the LINQ/Lamda should output same result as SQL query.
*I am new to SQL and LINQ
Thanks in advance.
Try this one:
var query =
from mv in MeasureValues
join m in Measures on mv.MeasureID equals m.ID
join p in Providers on mv.ProviderID equals p.ID
where mv.ReportingDate ==
(from mv2 in MeasureValues
where mv2.MeasureID == mv.MeasureID
orderby mv2.ReportingDate descending
select mv2.ReportingDate
).FirstOrDefault()
select new { m.InternalID, p.Code };
var distinct =
from q in query
group q by new { q.InternalID, q.Code} into gr
select new
{
InternalID = gr.First().InternalID,
Code = gr.First().Code
};
var result = distinct.ToList();
Another option to find max ReportingDate:
var query =
from mv in MeasureValues
join m in Measures on mv.MeasureID equals m.ID
join p in Providers on mv.ProviderID equals p.ID
where mv.ReportingDate == MeasureValues.Where(x => x.MeasureID == mv.MeasureID).Select(x => x.ReportingDate).Max()
select new { m.InternalID, p.Code };

Linq Queries - How to join the below two group by queries? On Course ID

I'm trying to join two group by queries to get one results set.
var query = from PP in _db.paymentPlans
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new {C,PP} by new {C.courseID} into totalRecievable
// Query 1
from PD in _db.paymentDetails
join PP in _db.paymentPlans on PD.paymentPlanID equals PP.paymentPlanID
join APP in _db.Applications on PP.applicationID equals APP.ApplicationId
join C in _db.Courses on APP.courseID equals C.courseID
where PP.active == true && APP.agentID == agentID
orderby C.courseID ascending
group new { C,PD } by new { C.courseID, C.cricosCode, C.courseName } into paymentsCourseWise
// Query 2
select new PdPpAppCourseModel
{
courseID = paymentsCourseWise.Key.courseID,
cricosCode = paymentsCourseWise.Key.cricosCode,
courseName = paymentsCourseWise.Key.courseName,
totalAmount = totalRecievable.Sum(x => x.PP.totalAmount),
paidAmount = paymentsCourseWise.Sum(x => x.PD.paidAmount)
}).ToList();
Total about is taken from query 1 as it should group in payment plan(PP) level.
You can only combine enumerations of the same type, you could project both to a common class and then concatenate them:
var result1 = db1.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });
var result2 = db2.table.Where(a=>a.value>0).Select( x=> new Foo() { //set props });
var resultSum = result1.Concat(result2);
Similarly you can apply this in your code and join this two groups.

Using multiple Join Methods instead of join in Linq To SQL

I want to using join method for the following queryin Linq To SQL
What works correctly:
var db = new DatabaseDataContext();
db.DeferredLoadingEnabled = false;
var q = from p in db.Persons
join c in db.Contacts on c.personId equal p.Id
join j in db.Jobs on j.personId equal p.Id
select SetPersonItems(p,c,j) ;
and what is SetPersonItems:
private Person SetPersonItems(Person p, Contact c, Job j)
{
p.Contact = c;
p.Job = j;
return p;
}
What I need:
Now I would like using of Join Method for the above query. Like:
var q = db.Persons.Join<......>(db.Contacts,...).Join<....>(db.Jobs,...).Select....
p.s. Later I will create a dynamic method for the above Multiple Join (Join methods)

SQL to Linq : Group by id but can't sum values

I am searching for equivalent to this query:
SELECT Prd.barcode , SumQUA = SUM(AType.unit*MIA.quantity)
FROM [dbo].[MerchantInventoryActivity] AS MIA
JOIN [dbo].[MerchantInventoryActivityType] AS AType ON (MIA.typeId = AType.id)
JOIN [dbo].[Product] AS Prd ON (MIA.productId = Prd.id)
WHERE MIA.invoiceId = '123'
GROUP BY Prd.barcode
i got stuck at the SumQUA = SUM(AType.unit*MIA.quantity) . Here's what I got so far:
(from mia in Entities.MerchantInventoryActivity
join Prd in Entities.Product on mia.productId equals Prd.id
join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
where mia.invoiceId == invoiceId
group Prd by Prd.barcode into g
select new
{
Barcode = g.Key,
SumQUA = // ??
}).ToList();
Thank you!
You can project first to anonymous type and then group:
(from mia in Entities.MerchantInventoryActivity
join Prd in Entities.Product on mia.productId equals Prd.id
join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
where mia.invoiceId == invoiceId
select new { Prd.barcode, AType.unit, MIA.quantity } into temp
group temp by temp.barcode into g
select new
{
Barcode = g.Key,
SumQUA = g.Sum(c => c.unit * c.quantity)
});
Add check for null when sum
(from mia in Entities.MerchantInventoryActivity
join Prd in Entities.Product on mia.productId equals Prd.id
join AType in Entities.MerchantInventoryActivityType on mia.typeId equals AType.id
where mia.invoiceId == invoiceId
select new { Prd.barcode, AType.unit, MIA.quantity } into temp
group temp by temp.barcode into g
select new
{
Barcode = g.Key,
SumQUA = g.Sum(c => c.unit??0 * c.quantity??0)
});

Categories

Resources