I have the following query I want to replicate in LINQ:
SELECT A.id,C.quotas, C.fundingid, C.date
,(SELECT value FROM public.fundingsharevalue WHERE fundingid = C.fundingid AND date = C.date) as sharevalue
FROM public.goal A
INNER JOIN public.goaltransactionfunding C ON A.id = C.goalid
where A.userid = 25
Code in LINQ:
var balance = from goal in _context.Goals
join goaltransactionfunding in _context.Goaltransactionfundings on goal.Id equals goaltransactionfunding.Goalid
join user in _context.Users on goal.Userid equals user.Id
where goal.Userid == userid
select new BalanceViewModel
{
FundingId = goaltransactionfunding.Fundingid,
ShareValue = (from fundingsharevalue in _context.Fundingsharevalues
where fundingsharevalue.Id == goaltransactionfunding.Fundingid && fundingsharevalue.Date.Equals(goaltransactionfunding.Date)
select fundingsharevalue.Value).FirstOrDefault(),
Quotas = (double)goaltransactionfunding.Quotas,
Fecha = goaltransactionfunding.Date,
GoalId = goal.Id
};
The problem is with Sharevalue subquery, it doesn't show values when actually it has.
It seems that the query does not fetch anything when it should fetch as it does in SQL.
I'm attaching images for both outputs.
QueryShareValues Image
LINQ sharevalues Image
Related
I am using LINQ query to get rows with joining multiple tables and also used let keyword to get the list of rows for displaying multiple values in a display column. What's wrong with this linq query?
ImageLink
(from app in _dbContext.Appointments
join patient in _dbContext.Patients on app.PatientID equals patient.ID
join doc in _dbContext.Doctors on app.DoctorID equals doc.ID
join avail in _dbContext.DoctorsAvailabilities on app.AvailabilityID equals avail.ID
join loc in _dbContext.OfficeLocations on app.LocationID equals loc.ID
join state in _dbContext.CategoryDetails on loc.USState equals state.ItemID into StateGroup
from state in StateGroup.DefaultIfEmpty()
join appoint in _dbContext.CategoryDetails on app.Status equals appoint.ItemID into AppointmentStatusGroup
from appoint in AppointmentStatusGroup.DefaultIfEmpty()
let reasonVisit = (from v in _dbContext.DoctorAppointmentVisitReasons
join c in _dbContext.CategoryDetails on v.ReasonID equals c.ItemID
where c.CategoryID == CatergoryConstant.ReasonofVisit && v.AppointmentID == app.ID
select c.MasterData).ToList()
join appointmentSource in _dbContext.CategoryDetails on app.AppointmentSource equals appointmentSource.ItemID into AppointmentSourceGroup
from appointmentSource in AppointmentSourceGroup.DefaultIfEmpty()
let getReport = (from st in _dbContext.DoctorReportStatus
join cat in _dbContext.CategoryDetails on st.ReportStatus equals cat.ItemID
where st.StatusID == StatusConstant.Active && st.AppointmentID == app.ID
select new DoctorReportStatusViewModel() { ReportStatusText = cat.MasterData, ReportStatus = st.ReportStatus, AppointmentID = st.AppointmentID }).ToList()
let specility = (from s in _dbContext.DoctorSpecialities
join c in _dbContext.CategoryDetails on s.SpecialitiesID equals c.ItemID
where c.CategoryID == CatergoryConstant.DoctorSpeciality && s.DoctorID == doc.ID
select c.MasterData).ToList()
I am having trouble converting this T-SQL code into EF C#
select
se.pcname, count(u.usrid) as total
from
tbusers as u
inner join
tbhcontainer as hc on u.hcid = hc.hcid
inner join
tbusersettings as se on hc.sid = se.sid
where
day(u.created) = 18
group by
se.pcname
order by
total desc
tbusers:
Username, PCName, Usrid, Created, HCID
tbhcontainer:
hcid, sid
tbusersettings:
sid, pcname
EDIT 1:
DateTime yesterday = DateTime.UtcNow.Date.AddDays(-1).AddHours(-3);
DB_121002_psmainEntities ctx = new DB_121002_psmainEntities();
var res = from r in ctx.tbusers
join hc in ctx.tbhcontainers on r.hcid equals hc.hcid
join s in ctx.tbUserSettings on hc.sid equals s.sid
group s by s.pcname
where r.created >= yesterday || r.created <= DateTime.Today
select r;
return res.Count();
It fails on all levels, just don't know how to use group by with joined tables
A direct translation would look more like this:
from u in ctx.Users
join hc in ctx.HContainers on u.Hcid equals hc.Hcid
join us in ctx.UserSettings on hc.Sid equals us.Sid
where u.Created.Day == 18
group u.Userid by us.Pcname into g
let total = g.Count()
orderby total descending
select new
{
pcname = g.Key,
total,
}
If you have additional clauses after the grouping, you need to place the results into another variable (g). Then you can access the group key and perform any aggregating function on that group.
I have following Sql query which joins two table and group by date and user Id
User Table
UserName UserId
LookupScannedHistory
HistoryId UserId ScannedDate ScannedCount
I have written following sql query to join table and group by on userId and Scanned Date removing Time varaint
SELECT
l.[UserID]
,CAST([ScannedDate] AS DATE)
,Sum([ScannedCount])
,[UserName]
FROM [dbo].[LookupScannedHistory] l
Join [dbo].[UserMaster] u
on l.UserID = u.UserId
group by l.UserId, u.UserName, CAST([ScannedDate] AS DATE)
I want to convert this into linq.
I have tried this
(from log in dataContext.LookupScannedHistories
join user in dataContext.UserMasters
on log.UserID equals user.UserId
where log.ScannedDate >= fiveDayPriorDate
orderby log.ScannedDate
group log by new
{
ScannedDateOnly = EntityFunctions.TruncateTime(log.ScannedDate),
log.UserID
} into dateClickedHistory
select dateClickedHistory
).ToList();
I have done this this gives what I want but I am unable to include username by combining join and group by
I found the solution.
var usersReportGroupList = (from log in dataContext.LookupScannedHistories
join user in dataContext.UserMasters
on log.UserID equals user.UserId
where log.ScannedDate >= fiveDayPriorDate
orderby log.ScannedDate
group new { user.UserName, log.ScannedCount,
log.ScannedDate}
by new
{
ScannedDateOnly =
EntityFunctions.TruncateTime(log.ScannedDate),
log.UserID,
user.UserName
}
into dateClickedHistory
select dateClickedHistory
).ToList();
var usersReportList = new List<LookupScannedHistoryDetails>();
foreach (var group in usersReportGroupList)
{
usersReportList.Add(new LookupScannedHistoryDetails()
{
ScannedCount = group.Sum(x => x.ScannedCount.Value),
ScannedDate = group.Key.ScannedDateOnly.Value,
UserId = group.Key.UserID.Value,
UniqueCount = group.Count(),
UserName = group.Key.UserName
});
}
I have two related tables Ticket and Status.
Every ticket can be multiple status. (Open, assigned, closed). But I want all tickets but only one status (newest date) to show.
I could handle with this query on t-sql;
SELECT d.ticketID, statusName, c.statusDate, c.assignedTo,c.statusID
FROM Ticket d LEFT JOIN Status c ON c.ticketID = d.ticketID
WHERE c.statusID = (
SELECT MAX(statusID)
FROM Status c2
WHERE c2.ticketID = d.ticketID)
This is my Linq :
var result = from t in db.Ticket
join s in db.Status.OrderByDescending(x=>x.statusDate).Take(1)
on t.ticketID equals s.ticketID join c in db.Customer
on t.customerID equals c.customerID
But this only returning one row.
I solve my problem with linqer application via converting my Tsql query to linq
from s in db.Status
where s.statusID ==
(from c2 in db.Status where
c2.ticketID == s.Ticket.ticketID &&
c2.statusName == "New" ||
c2.statusName == "Assigned"
select new
{
c2.statusID
}).Max(p => p.statusID)
Thanks for everyone.
Try changing your original linq logic to:
var result = from t in db.Ticket
join s in db.Status on t.ticketID equals s.ticketID into sGroup
from s in sGroup.OrderByDescending(x=>x.statusDate).Take(1)
join c in db.Customer
on t.customerID equals c.customerID
I need translate next sql to linq is it possible? That will have approximately the same speed
SELECT Count(tblcollectionimage.lngimageid),
tblcollectiontree.lngcollectionid,
tblcollection.txtname
FROM (tblcollectiontree
LEFT JOIN tblcollectionimage
ON blcollectiontree.lngcollectionid =
tblcollectionimage.lngcollectionid)
JOIN tblcollection
ON tblcollectiontree.lngcollectionid = tblcollection.lngcollectionid
WHERE lngcollectionparentid = 0
GROUP BY tblcollectiontree.lngcollectionid,
tblcollection.txtname
I have currently such linq but it doesn't work.
var results =(from collection in dataBase.tblcollections
join collectionTree in dataBase.tblcollectiontrees on
collection.lngcollectionid equals collectionTree.lngcollectionid
into generalCollections
from generalCollection in generalCollections
join images in dataBase.tblcollectionimages on
collection.lngcollectionid equals images.lngcollectionid
into generalCollectionImages
from generalCollectionImage in
generalCollectionImages.DefaultIfEmpty()
group generalCollectionImage by
generalCollectionImage.lngcollectionid into hello
from hellos in hello.DefaultIfEmpty()
join collection in dataBase.tblcollections on
hello.Key equals collection.lngcollectionid
select new
{
id = hello.Key,
name = hello.Count()
}).ToList();