As I am new to Linq and Entity Framework.
The following is my working stored procedure which includes a value that is a comma separated string (the SUBSTRING clause)
SELECT DISTINCT
SR.StudentRequestId,
SR.RegistrationId,
SR.Location,
SR.PaymentMethod,
SR.CreatedOn,
C.ClassName,
CC.CampusName,
CASE WHEN ISNULL(TSR.StatusId,0)=0 THEN 1 ELSE TSR.StatusId END AS StatusId,
SUBSTRING(
(SELECT', ' + REPLACE(REPLACE(ST1.FromTime,'AM',''),'PM','') + '-'+ ST1.ToTime AS [text()]
FROM dbo.StudentRequestTimings ST1
WHERE ST1.StudentRequestId = SRT.StudentRequestId
ORDER BY ST1.CreatedOn FOR XML PATH ('')
), 2, 1000) [Time] FROM StudentRequest SR
INNER JOIN Registration R ON R.RegistrationId = SR.RegistrationId
INNER JOIN Campus CC ON CC.CampusId = R.CampusId
INNER JOIN Class C ON C.ClassId = SR.ClassId
LEFT JOIN TutorClasses TC ON SR.ClassId = TC.ClassId
LEFT JOIN StudentRequestTimings SRT ON SR.StudentRequestId = SRT.StudentRequestId
LEFT JOIN TutorStudentRequest TSR ON TSR.StudentRequestId = SRT.StudentRequestId AND TutorId = #RegistrationId
WHERE TC.RegistrationId = #RegistrationId
ORDER BY SR.CreatedOn DESC
I have a requirement to use this data in a PagedList method that accepts a IQueryable<T> and I want to convert this SP to a LINQ query that returns a IQueryable (internally the PagedList method uses .Skip() and .Take() to perform server side paging).
The following is my attempt so far, but I do not know why i am not getting to get the expected result as getting from SQL query. I think some thing is wrong in my below code. Can any one identify what is wrong in below code?
var model = (from sr in db.StudentRequests
join r in db.Registrations on sr.RegistrationId equals r.RegistrationId
join cc in db.Campus on r.CampusId equals cc.CampusId
join c in db.Classes on sr.ClassId equals c.ClassId
from tc in db.TutorClasses.Where(t => t.ClassId == sr.ClassId).DefaultIfEmpty()
from srt in db.StudentRequestTimings.Where(s => s.StudentRequestId == sr.StudentRequestId).DefaultIfEmpty()
from tsr in db.TutorStudentRequests.Where(t => t.StudentRequestId == srt.StudentRequestId && t.TutorId == registrationid).DefaultIfEmpty()
where tc.RegistrationId == registrationid
select new TutorDashboard
{
StudentRequestId = sr.StudentRequestId,
RegistrationId = sr.RegistrationId,
Location = sr.Location,
PaymentMethod = sr.PaymentMethod,
CreatedOn = sr.CreatedOn,
ClassName = c.ClassName,
CampusName = cc.CampusName,
Time = string.Join(",", db.StudentRequestTimings.Where(p => p.StudentRequestId == sr.StudentRequestId).Select(p => p.FromTime.ToString().Replace("AM", "").Replace("PM", "") + "-" + p.ToTime.ToString())),
}).Distinct();
Can any one help me out for why I am not getting proper result from above linq query?
Issue is that on adding below code to Linq I am facing issue, How can I resolve this
Time = string.Join(",", db.StudentRequestTimings.Where(p => p.StudentRequestId == sr.StudentRequestId).Select(p => p.FromTime.ToString().Replace("AM", "").Replace("PM", "") + "-" + p.ToTime.ToString())),
I had added this code because I want to get a single string from multiple row
1:00-1:30 PM, 2:00=2:30 PM
5:00-5:30 PM
Like wise
As there was an issue in converting comma seperated code I had implement below code
var query = (from sr in db.StudentRequests
join r in db.Registrations on sr.RegistrationId equals r.RegistrationId
join cc in db.Campus on r.CampusId equals cc.CampusId
join c in db.Classes on sr.ClassId equals c.ClassId
from tc in db.TutorClasses.Where(t => t.ClassId == sr.ClassId).DefaultIfEmpty()
from srt in db.StudentRequestTimings.Where(s => s.StudentRequestId == sr.StudentRequestId).DefaultIfEmpty()
from tsr in db.TutorStudentRequests.Where(t => t.StudentRequestId == srt.StudentRequestId && t.TutorId == registrationid).DefaultIfEmpty()
where tc.RegistrationId == registrationid
select new
{
StudentRequestId = sr.StudentRequestId,
RegistrationId = sr.RegistrationId,
Location = sr.Location,
PaymentMethod = sr.PaymentMethod,
CreatedOn = sr.CreatedOn,
ClassName = c.ClassName,
CampusName = cc.CampusName,
StatusId = tsr.StatusId == null ? 1 : tsr.StatusId,
Time = db.StudentRequestTimings.Where(p => p.StudentRequestId == sr.StudentRequestId).Select(p => p.FromTime.ToString().Replace("AM", "").Replace("PM", "") + "-" + p.ToTime)
}).ToList().GroupBy(p => new { p.StudentRequestId }).Select(g => g.First()).ToList();
var model = query.AsEnumerable().Select(x => new TutorDashboard
{
StudentRequestId = x.StudentRequestId,
RegistrationId = x.RegistrationId,
Location = x.Location,
PaymentMethod = x.PaymentMethod,
CreatedOn = x.CreatedOn,
ClassName = x.ClassName,
CampusName = x.CampusName,
StatusId = x.StatusId == null ? 1 : x.StatusId,
Time = string.Join(",", x.Time),
}).ToList().ToPagedList(page ?? 1, 1);
May this code will be helpful to some who need comma separated value with multiple left join
Related
I'm working on this conference app where I have to return certain values from the different table using join queries using LINQ
from a in db.ApplySchedule
join b in db.userdetails on a.UserID equals b.UserId
join c in db.roomdetails on a.RoomID equals c.RoomId
join d in db.VideoFiles on a.RoomID equals d.RoomId where d.IsActive == true || d.IsActive==false
join e in db.ImageFiles on a.RoomID equals e.RoomId where e.IsActive == true|| e.IsActive==false
where EntityFunctions.TruncateTime(a.MDate) == EntityFunctions.TruncateTime(DateTime.Now) && a.RoomID == id
&& a.Status == true
select new ShedulerViewModel
{
Id = a.BookingID,
UserId = a.UserID,
Uname = b.UserName,
RoomId = a.RoomID,
Rname = c.RoomName.ToUpper(),
Organizer = a.SubjectDetail,
Date = a.MDate,
FromTime = a.start_date,
ToTime = a.end_date,
//Accesseries = a.Accesseries,
attend = a.Attend,
VideoID = d.RoomId,
VideoPath = d.FilePath,
videoIsActive= d.IsActive,
ImageId = e.RoomId,
ImagePath = e.FilePath,
ImageIsActive = e.IsActive
};
Here is the problem, I'm able to get the values if the last two tables db.imagefiles and db.videofiles has matching values but incase it doesn't I'm getting 0 value from all the other tables even though there are rows with matching id, how do I overcome this? I want to pass value even if the video and image tables have no rows.
I need to query a table and join related tables. A single query without joining another table returns the expected result. but once I join another table I get zero result.
The below query returns some results
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
But once I join another table
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate);
join v in context.Venue on o.Id equals v.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I also try the below query and I still get zero result
var response = from o in context.Orders.Where(p => p.Start_Effective >= startDate && p.Start_Effective < endDate)
from v in context.Venue
where v.OrderId == o.Id
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
};
I cant figure out why this is returning 0 result once I join table
If there is no record in Venue Table with OrderId, when inner join is used, no data returned and you should insert a record that has OrderId that exist in Order Table.
Another option is using left join.
By left join, if there is no OrderId in Venue Table, result was returned
try to use a left join, and add to list
var response = (from o in contextOrders
join v in context.Venue on o.Id equals v.Id into vj
from v in vj.DefaultIfEmpty()
where ( o.Start_Effective >= startDate && o.Start_Effective < endDate)
select new
{
Id = o.Id,
PointId = o.FromPointId,
VenueName = v.Name
}).ToList();
I'm using Linq (code-first approach) query to retrieve the data from DB and couldn't able to get similar result while using below linq query:
from msi in db.MainSaleInvoiceTbls
join dsi in db.DetialSaleInvoiceTbls on msi.Id equals dsi.MainSaleInvoiceId
join ca in db.CustomerAccounts on msi.CustomerId equals ca.Id
join cg in db.MiscLists on ca.CustomerGroupId equals cg.Id
where msi.IsActive == true && msi.CompanyId == UniversalInfo.UserCompany.Id && msi.MainSaleInvoiceDataType == MainSaleInvoiceType.SOInvoice
group msi by new { dsi,msi.Date,msi.FinancialVoucher,msi.SaleOrderPrefix,msi.SaleOrderNumber,msi.SalesId,ca.CustomerName,ca.AccountCode,cg.Name }
into mainSaleInvoice
from dx in mainSaleInvoice.DefaultIfEmpty()
// orderby main.Id
select new
{
Date = mainSaleInvoice.Key.Date,
Voucher = mainSaleInvoice.Key.FinancialVoucher,
InvoiceAccount = mainSaleInvoice.Key.AccountCode,
CustomerName = mainSaleInvoice.Key.CustomerName,
CustomerGroup = mainSaleInvoice.Key.Name,
Invoice = mainSaleInvoice.Key.SaleOrderPrefix + mainSaleInvoice.Key.SaleOrderNumber,
PurchaseOrder = mainSaleInvoice.Key.SalesId,
SalesTax = "",
InvoiceAmount = mainSaleInvoice.Sum(x => (Double)(mainSaleInvoice.Key.Quantity * mainSaleInvoice.Key.UnitPrice))
}).ToList()
In linq, i need to get shortdatetimeString() and sum() of (unitprice* quantity) from child table DetialSaleInvoiceTbls
being new in query writing, I don't know where and what I'm doing wrong. Any suggestions would be much appreciated.
var list=from msi in db.MainSaleInvoiceTbls
join dsi in db.DetialSaleInvoiceTbls on msi.Id equals dsi.MainSaleInvoiceId
join ca in db.CustomerAccounts on msi.CustomerId equals ca.Id
join cg in db.MiscLists on ca.CustomerGroupId equals cg.Id into a
where msi.IsActive == true && msi.CompanyId == UniversalInfo.UserCompany.Id
&& msi.MainSaleInvoiceDataType == MainSaleInvoiceType.SOInvoice
from cg in a.DefaultIfEmpty()
select new
{mainSaleInvoice.Date,
mainSaleInvoice.FinancialVoucher,mainSaleInvoice.AccountCode,
mainSaleInvoice.CustomerName,mainSaleInvoice.Name,
mainSaleInvoice.SaleOrderPrefix, mainSaleInvoice.SaleOrderNumber,
mainSaleInvoice.SalesId, }).sum(x=>x. (mainSaleInvoice.Quantity *
mainSaleInvoice.UnitPrice)).groupby msi new
{msi.Date,msi.FinancialVoucher,msi.SaleOrderPrefix,msi.SaleOrderNumber,
msi.SalesId};
Date = mainSaleInvoice.Date;
Voucher = mainSaleInvoice.FinancialVoucher;
InvoiceAccount = mainSaleInvoice.AccountCode;
CustomerName = mainSaleInvoice.CustomerName;
CustomerGroup = mainSaleInvoice.Name;
Invoice = mainSaleInvoice.SaleOrderPrefix +
mainSaleInvoice.SaleOrderNumber;
PurchaseOrder = mainSaleInvoice.SalesId;
SalesTax = "";
InvoiceAmount =list;
I am attaching my full query in which ps.productId is returning list of strings and I want all strings comma separated as a single string like "a,b,c"
How can I achieve this using lambda expression!
ProductIDs = string.Join(",", ps.ProductID),
ProductIDs = string.Join(",", _DataContext.ProductSelectionEntity.Where(x => x.BillingId == bill.Id).Select(x => x.ProductID).ToList())
ps.productIds will return a List<string>, I want it in a string format "1,2,3,4"
var results = (from uastatus in _DataContext.UaStatusEntity
where uastatus.IsUaComplete == false
join client in _DataContext.Client on uastatus.ClientID equals client.ClientID
where client.ClientStatus == "Active" &&
client.IsEnrolledNHCR.HasValue &&
client.IsEnrolledNHCR.Value
join ps in _DataContext.ProductSelectionEntity on bill.ClientId equals ps.ClientID
where bill.Id == ps.BillingId
select new PendingUA
{
ClientId = client.ClientID,
ClientRelationship = client.ClientRelationship,
ClientName = client.ClientName,
EIN = client.EIN,
ProductIDs = string.Join(",", ps.ProductID),
ProductIDs = string.Join(",",_DataContext.ProductSelectionEntity.Where(x => x.BillingId == bill.Id).Select(x => x.ProductID).ToList())
}).Distinct().ToList();
Error message
You must extract value from database before use string.Join
var resultsFromDB = (from uastatus in _DataContext.UaStatusEntity
where uastatus.IsUaComplete == false
join client in _DataContext.Client on uastatus.ClientID equals client.ClientID
where client.ClientStatus == "Active" &&
client.IsEnrolledNHCR.HasValue &&
client.IsEnrolledNHCR.Value
join ps in _DataContext.ProductSelectionEntity on bill.ClientId equals ps.ClientID
where bill.Id == ps.BillingId
select new
{
ClientId = client.ClientID,
ClientRelationship = client.ClientRelationship,
ClientName = client.ClientName,
EIN = client.EIN,
ProductID = ps.ProductID,
}).ToList();
var results = (from value in resultsFromDB
let ProductIDS = string.Join(",", resultsFromDB.Where(x => x.ClientId == value.ClientId ).Select(x => x.ProductID).ToList())
select new PendingUA
{
ClientId = value.ClientID,
ClientRelationship = value.ClientRelationship,
ClientName = value.ClientName,
EIN = value.EIN,
ProductIDS = ps.ProductIDS ,
}).Distinct().ToList();
for better performance, use linq group by
I'm trying to track down a crash in some existing code in a web app I inherited.. I've traced this down to a single LINQ expression:
var projInfo = (from v in context.TPM_PROJECTVERSION
join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID
join pt in context.TPM_PROJECTTYPES on p.PROJECTTYPEID equals pt.PROJECTTYPEID
where v.PROJECTID == projectId && v.VERSIONID == versionId
select new
{
ProjectName = v.NAME,
ProjectType = pt.SHORTNAME,
ProjectDesc = v.DESCRIPTION,
BusinessLaunchData = p.BUSINESSLAUNCHDATE,
BusinessSponsor = (v.TPM_USER3.FIRSTNAME + " " + v.TPM_USER3.LASTNAME),
PrimaryTrainingOwner = (pto.FIRSTNAME + " " + pto.LASTNAME)
}).First();
The error is "Sequence contains no elements", which I've traced to this line:
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID
If USER1 is null, the row does not get returned. Instead, I need PrimaryTrainingOwner to just be null or blank instead. Basically, I need to do a LEFT JOIN instead and check for this while setting PrimaryTrainerOwner. Is there a way to update this LINQ expression to handle this case? Thanks!
I think I found a solution. I'd appreciate any comments on whether this is the best approach or syntax or whatever. Thanks!
var projInfo = (from v in context.TPM_PROJECTVERSION
join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID into primaryowner
from subpto in primaryowner.DefaultIfEmpty()
join pt in context.TPM_PROJECTTYPES on p.PROJECTTYPEID equals pt.PROJECTTYPEID
where v.PROJECTID == projectId && v.VERSIONID == versionId
select new
{
ProjectName = v.NAME,
ProjectType = pt.SHORTNAME,
ProjectDesc = v.DESCRIPTION,
BusinessLaunchData = p.BUSINESSLAUNCHDATE,
BusinessSponsor = (v.TPM_USER3.FIRSTNAME + " " + v.TPM_USER3.LASTNAME),
PrimaryTrainingOwner = subpto == null ? String.Empty : (subpto.FIRSTNAME + " " + subpto.LASTNAME)
}).First();