SQL to LINQ C# EntityFramework - c#

I'm on my way to convert all my straight SQL programms to Entity Framework.
So I need LINQ and LE.
But I'm not able to do this in LINQ:
SELECT
a.abteilung,
sum(d.kosten)
FROM
tdaten d,
abteilung a
WHERE
d.sourcenr = a.sourcenr AND
d.datum between '" + string.Format("{0:yyyy-MM-dd}", DTP_from.Value) + "'
and '"+string.Format(format: "{0:yyyy-MM-dd}", arg0: DTP_to.Value)+"'
GROUP BY
a.abteilung;", _con);
Thanks

Something like this?
from a in abteilung
join d in tdaten
on a.sourcenr equals d.sourcenr
where d.datum >= DTP_from.Value && d.datum <= DTP_to.Value
group d by a.abteilung into g
select new
{
abteilung = g.Key,
kosten = g.Sum(d => d.kosten)
}

An option.
The whole can b breakdown into 3 sub-queries in LINQ.
Get the Records
Take the sum
The group by the result.
Following are the queries.:
var results = from a in abteilung
join d in tdated on d.sourcenr equals a.sourcenr
where
d.dateum >= fromDate && d.datum <= ToDate.AddDays(1)
select new {a.abteilung, d.kosten};
var sumOfKotsen = results.Sum(x=>x.kosten);
var groupResult = results.GroupBy(x=>x.abteilung);
Assuming that the dateFrom and ToDate are the DateTime objects.

Related

Sum Columns from joined tables to get a calculated value using Linq to SQL

In the above diagram for each customer I want to select all orders and then for each order I have calculate a TotalPrice = (Sum of all Food Items included in order * Quantity) + ExtraPrice. I am struggling to create a query for it using linq to sql.
var res = (from a in dc.orders
join b in dc.orderLines on a.orderId equals b.fk_orderId
join c in dc.foodItems on b.fk_foodId equals c.foodId
where a.fk_custId == cID
group new { a,c,b } by a into g
select new
{
OID1 = g.Key.orderId,
date1 = g.Key.date.Value.Date,
price1 = g.Sum(x => x.c.price * x.b.quantity) + g.Key.orderLines.Select(o => o.extraPrice).Sum()
});
Given above is linq query I was looking for.
Should be something close to this. I'm not around a computer to test so let me know if you get errors.
db.orders.Select(o => new { o.orderid, o.date, TotalPrice = ( (o.orderLines.Select(ol => ol.food items.Count()).Sum() * o.Quantity) + o.extraPrice) } )

Converting SQL to Linq in c#

I am trying to convert some SQL Code to c# Linq:
SELECT Username, Count(Ticket.TicketId) as 'Tickets Completed'
FROM Ticket
INNER JOIN TicketStatus ON Ticket.TicketStatusID = TicketStatus.TicketStatusID
INNER JOIN Membership ON Ticket.CompletedBy = Membership.UserId
WHERE Ticket.ClosedDate >= #StartDate
and Ticket.ClosedDate <= #EndDate
GROUP BY Username
ORDER BY 'Tickets Completed' DESC
which displays
Paul 6
Mike 4
Donna 3
Elliot 2
I tried to use Linqer which made this more complicated and didnt return any results:
var query = from Ticket in data.Tickets
join Membership in data.Memberships on new { CompletedBy = Guid.Parse(Ticket.CompletedBy.ToString()) } equals new { CompletedBy = Membership.UserId }
where
Ticket.ClosedDate >= StartDate &&
Ticket.ClosedDate <= EndDate
group new { Membership, Ticket } by new
{
Membership.Username
} into g
orderby
"Tickets Completed" descending
select new
{
Username = g.Key.Username,
Completed = g.Count(p => p.Ticket.TicketID > 0)
};
Your help would be appreciated.
Thanks
Assuming CompletedBy and UserId columns are both uniqueidentifier in the database, you shouldn't need to do any type conversion.
var query = from t in db.ticket
join ts in db.ticketStatus
on t.TicketStatus.ID equals ts.TicketStatusID
join m in db.Membership
on t.CompletedBy equals m.UserId
where t.ClosedDate >= startDate
&& t.closedDate <= endDate
group t by m.UserName into tGroup
order by tGroup.Count(t=> t.TicketId) decending
select new {
UserName = tGroup.Key,
TicketCount = tGroup.Count()
};

How do I sum a column in a child table of a projected linq query?

I'm still pretty green on linq when it comes to projection and grouping. How can I get the results of the following SQL query using linq? Or is there a better approach to retrieving this query besides linq? I'm using entity framework and I know I can just hard code the sql but would prefer not to do that if there is a better way.
SELECT j.JobId, j.Name, j.OrderId, j.ShipDate,
st.ShipTypeId, sum(p.DeliveryCnt * p.Quantity) AS 'DeliveryCnt'
FROM Jobs j
JOIN ShipTo st ON j.JobId = st.JobId
JOIN DesignSets ds ON j.JobId = ds.JobId
JOIN DesignSetAreas dsa ON ds.DesignSetId = dsa.DesignSetId
JOIN Products p ON dsa.DesignSetAreaId = p.DesignSetAreaId
WHERE j.ShipDate >= '11/13/2016' AND j.ShipDate <= '11/26/2016'
GROUP BY j.JobId, j.Name, j.OrderId, j.ShipDate, st.ShipTypeId
The below code is what I have so far, but I'm not sure where or how I would do the grouping, or if this is even possible.
var shipList = from j in db.Jobs
join st in db.ShipTo on j.JobId equals st.JobId
join ds in db.DesignSets on j.JobId equals ds.JobId
join p in db.Products on ds.DesignSetId equals p.DesignSetId
where j.ShipDate >= startDate && j.ShipDate <= endDate
select new ShipScheduleViewModel
{
JobId = j.JobId,
Name = j.OrderId + " " + j.Name,
ShipDay = ((DateTime)j.ShipDate).Day,
ShipVia = st.ShipTypeId,
Count = p.DeliveryCnt * p.Quantity
};
Basically the group by syntax requires you to say what you want in the grouping (in this case the p Products are what you are aggregating in the select) and the values you want to group by (in this case the j Job and st.ShipTypeId) and finally you assign the grouping into a variable you can use in your select.
var shipList = from j in db.Jobs
join st in db.ShipTo on j.JobId equals st.JobId
join ds in db.DesignSets on j.JobId equals ds.JobId
join p in db.Products on ds.DesignSetId equals p.DesignSetId
where j.ShipDate >= startDate && j.ShipDate <= endDate
group p by new { j, st.ShipTypeId } into grp
select new ShipScheduleViewModel
{
JobId = grp.Key.j.JobId,
Name = grp.Key.j.OrderId + " " + grp.Key.j.Name,
ShipDay = ((DateTime)grp.Key.j.ShipDate).Day,
ShipVia = grp.Key.ShipTypeId,
Count = grp.Sum(p => p.DeliveryCnt * p.Quantity)
};

LINQ to Entities does not recognize ToString using query syntax

I'm getting this error in a LINQ query (query syntax used). In the past I've gotten this error when using dot syntax in my LINQ query so all I had to do is a call to ToList() and then select using an anonymous class. But in my case where I'm now using query syntax, how do I do the same thing? Yes I'm using EF.
Here is the code:
var dataList = from h in context.Horaires
join e in context.Employes on h.iIdEmploye equals e.iIdEmploye
join p in context.Postes on h.iIdPoste equals p.iIdPoste
join g in context.GroupesPostes on p.iIdGroupePoste equals g.iIdGroupePoste
join en in context.EnsemblesPostes on g.iIdEnsemblePoste equals en.iIdEnsemblePoste
join d in context.Departements on e.iIdDepartement equals d.iIdDepartement
where p.bitActif == true && h.dteDate == p.dteDate
orderby e.sIdEmployeClient
select new ScenarioScheduleItemModel
{
H = "D",
EmployeeSchedule = "EmployeeSchedule",
EmployeeSchedule2 = "EmployeeSchedule",
EmployeeXrefCode = e.sIdEmployeClient,
// ToString used here for StartTime and EndTime
StartTime = h.dteDate.ToString(CultureInfo.InvariantCulture).Substring(0, 10) + "T" + p.dteHeureDebut.ToString(CultureInfo.InvariantCulture).Substring(11, 8),
EndTime = h.dteDate.ToString(CultureInfo.InvariantCulture).Substring(0, 10) + "T" + p.dteHeureFin.ToString(CultureInfo.InvariantCulture).Substring(11, 8),
DeptXrefCode = d.sNom,
JobXrefCode = p.sNom,
OrgUnit = string.Empty,
XrefCode = string.Empty,
OrgLocationTypeXrefCode = string.Empty,
PayAdjCodeXrefCode = string.Empty
};
var result = dataList.Distinct().ToList();
You could just select the "raw" values then use AsEnumerable and a Select to get the desired values
var dataList = (from h in context.Horaires
...
select new { e, h, p, d }).AsEnumerable()
.Select(anon => new ScenarioScheduleItemModel
{
...
StartTime = anon.h.dteDate.ToString(CultureInfo.InvariantCulture)
.Substring(0, 10)
+ "T" + anon.p.dteHeureDebut.ToString(CultureInfo.InvariantCulture)
.Substring(11, 8),
EndTime = anon.h.dteDate.ToString(CultureInfo.InvariantCulture)
.Substring(0, 10)
+ "T" + anon.p.dteHeureFin.ToString(CultureInfo.InvariantCulture)
.Substring(11, 8),
...
});
It may make more sense to use something like string.Format
StartTime = string.Format("{0:MM/dd/yyyy}T{1:hh:mm:ss}", h.dteDate, p.dteHeureDebut),
EndTime = string.Format("{0:MM/dd/yyyy}T{1:hh:mm:ss}", h.dteDate, p.dteHeureFin),
Just for your info. here's a generic form what you need to do:
var dbQuery = from x in db.Table
// do stuff with x what will be translated to SQL
select x;
var memoryQuery = from z in dbQuery.AsEnumerable() // <-- !
// do stuff with z in memory
select z;

linq groupby question

I have a table that has several columns: HarvestID, HarvestDate, UserID to mention the main ones.
For each date, there are going to be several HarvestID per day.
So far, I have the following linq query:
TheUserID and TheMonth are passed in as an int and a DateTime
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
from d in TheDays
select new
{
TheDay = d.HarvestDate.Date,
TheDayCount = (from c in TheDay
select c.HarvestID).Count()
};
I'm looking to have the output be a list of counts per day. The query doesn't bug but the problem is that at the moment the query is not returning a unique row for each day. The grouping doesn't work and I'm not finding out why. What's wrong with this code?
Thanks.
It think your query should be
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
where h.HarvestDate.Month == TheMonth.Month
where h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into TheDays
select new
{
TheDay = TheDays.Key,
TheDayCount = TheDays.Count()
};
Here is a vry good refrence to above group by statement http://msdn.microsoft.com/en-us/vcsharp/aa336754.aspx#simple1
var MyQuery = from h in MyDC.HarvestTable
where h.UserID == TheUserID
&& h.HarvestDate.Month == TheMonth.Month
&& h.HarvestDate.Year == TheMonth.Year
group h by h.HarvestDate.Day into g
select new
{
TheDay = g.Key,
TheDayCount = g.Count()
};
This will not give you zeroes on the days where there is no data - but should give you a count where there is.
http://msdn.microsoft.com/en-us/vcsharp/aa336746 is my go-to page for LINQ examples.

Categories