Crystal Report - Linq select statement finds nulls in fields - linq

I'm trying to use a Linq query to a custom crystal report in MyReports folder. However, crystal reports engine is complaining of nulls.
I have managed to make a blank for the Serial Number where it might be null, but DateTime is more of an issue for me.
I have tried:
InspectionDate = subpat.InspectionDate == null ? "" : subpat.InspectionDate,
But the error is:
Type of conditional expression cannot be determined because there is no implicit conversion between 'string' and 'System.DateTime?'
I would just want a blank result if null.
My Query:
var today = DateTime.Now.Date;
var tomorrow = today.AddDays(30);
var dateresult = db.ClinicalINSs.GroupBy(d => d.ClinicalAssetID)
.SelectMany(g => g.OrderByDescending(d => d.NextInspectionDate)
.Take(1));
var ClinicalIDVM = (from s in dateresult.Where(q => q.NextInspectionDate <= tomorrow)
join co in db.ClinicalAssets on s.ClinicalAssetID equals co.ClinicalAssetID into AR
let subred = AR.OrderByDescending(subredASS => subredASS.ClinicalAssetID).FirstOrDefault()
join cp in db.ClinicalPATs on s.ClinicalAssetID equals cp.ClinicalAssetID into AP
let subpat = AP.OrderByDescending(SubPATASS => SubPATASS.ClinicalAssetID).FirstOrDefault()
orderby s.NextInspectionDate descending
select new ClinicalIDVM
{
ClinicalAssetID = s.ClinicalAssetID,
ProductName = subred.ProductName,
SerialNo = subred.SerialNo == null ? "" : subred.SerialNo,
InspectionDate = subpat.InspectionDate,
NextInspectionDate = s.NextInspectionDate
}).ToList();

You can try this way
InspectionDate = subpat.InspectionDate == null ? (DateTime?)null : subpat.InspectionDate
or change type of InspectionDate to string, then you will do
InspectionDate = subpat.InspectionDate.HasValue
? subpat.InspectionDate.Value.ToString("yyyy-MM-dd") : "";
Updated
InspectionDate = subpat.InspectionDate == null ? (object) "" : subpat.InspectionDate

Related

Linq query averages

I can run this in Linqpad and it works fine but in VS when i run it the result throws errors because of the Avg, Max and Min statements. Can anyone advise how i need to change this to get the desired result?
tickets = from t in dbContext.TblOmTasks
join o in dbContext.TblOms on t.OMID equals o.OMID
join ls in dbContext.LkpStatusBasics on t.OMTaskStatus equals ls.ID
where t.OMID == SiteId
where ls.Status.Contains(status)
group t by new { Y = t.Created.Value.Date.Year, M = t.Created.Value.Date.Month } into grp
orderby grp.Key.M
select new TBS
{
Month = new DateTime(grp.Key.Y, grp.Key.M, 1).ToString("MMM", CultureInfo.InvariantCulture)
,Avg = grp.Average(g => Convert.ToInt32((g.Updated.HasValue ? g.Updated - g.Created : DateTime.Now - g.Created).Value.Days))
,Max = grp.Max(g => Convert.ToInt32((g.Updated.HasValue ? g.Updated - g.Created : DateTime.Now - g.Created).Value.Days))
,Min = grp.Min(g => Convert.ToInt32((g.Updated.HasValue ? g.Updated - g.Created : DateTime.Now - g.Created).Value.Days))
};
Looks like EF Core still can not translate Timestamp.Days. So use appropriate functions.
tickets =
from t in dbContext.TblOmTasks
join o in dbContext.TblOms on t.OMID equals o.OMID
join ls in dbContext.LkpStatusBasics on t.OMTaskStatus equals ls.ID
where t.OMID == SiteId
where ls.Status.Contains(status)
group t by new { Y = t.Created.Value.Date.Year, M = t.Created.Value.Date.Month } into grp
orderby grp.Key.M
select new TBS
{
Month = new DateTime(grp.Key.Y, grp.Key.M, 1).ToString("MMM", CultureInfo.InvariantCulture),
Avg = grp.Average(g => EF.Functions.DateDiffDay(g.Created, g.Updated ?? DateTime.Now),
Max = grp.Max(g => EF.Functions.DateDiffDay(g.Created, g.Updated ?? DateTime.Now),
Min = grp.Min(g => EF.Functions.DateDiffDay(g.Created, g.Updated ?? DateTime.Now)
};

Linq Join table AND nullable variable

I'm trying to make a LINQ Query on Ef6 using a join on the db.ClincalAssets table where the AssetDisposalID Field is null
i.e. I don't want rows of data from that table where the AssetDisposalID is not null
The following code doesn't appear to work because it returns the same 23 results I had before I modified the code
var today = DateTime.Now.Date;
var tomorrow = today.AddDays(30);
var dateresult = db.ClinicalINSs.GroupBy(d => d.ClinicalAssetID)
.SelectMany(g => g.OrderByDescending(d => d.NextInspectionDate)
.Take(1));
var ClinicalIDVM = (from s in dateresult.Where(q => q.NextInspectionDate <= tomorrow)
join co in db.ClinicalAssets.Where (t => t.AssetDisposalID == null) on s.ClinicalAssetID equals co.ClinicalAssetID into AR
let subred = AR.OrderByDescending(subredASS => subredASS.ClinicalAssetID).FirstOrDefault()
join cp in db.ClinicalPATs on s.ClinicalAssetID equals cp.ClinicalAssetID into AP
let subpat = AP.OrderByDescending(SubPATASS => SubPATASS.ClinicalAssetID).FirstOrDefault()
orderby s.NextInspectionDate descending
select new ClinicalIDVM
{
ClinicalAssetID = s.ClinicalAssetID,
ProductName = subred.ProductName ,
SerialNo = subred.SerialNo == null ? "" : subred.SerialNo,
InspectionDate = subpat.InspectionDate,
NextInspectionDate = s.NextInspectionDate == null ? (DateTime?)null : s.NextInspectionDate,
}).ToList();
i have also tried this:
var today = DateTime.Now.Date;
var tomorrow = today.AddDays(30);
var dateresult = db.ClinicalINSs.GroupBy(d => d.ClinicalAssetID)
.SelectMany(g => g.OrderByDescending(d => d.NextInspectionDate)
.Take(1));
var ClinicalIDVM = (from s in dateresult from Disp in db.ClinicalAssets where s.NextInspectionDate <= tomorrow && Disp.AssetDisposalID == null
join co in db.ClinicalAssets on s.ClinicalAssetID equals co.ClinicalAssetID into AR
let subred = AR.OrderByDescending(subredASS => subredASS.ClinicalAssetID).FirstOrDefault()
join cp in db.ClinicalPATs on s.ClinicalAssetID equals cp.ClinicalAssetID into AP
let subpat = AP.OrderByDescending(SubPATASS => SubPATASS.ClinicalAssetID).FirstOrDefault()
orderby s.NextInspectionDate descending
select new ClinicalIDVM
{
ClinicalAssetID = s.ClinicalAssetID,
ProductName = subred.ProductName ,
SerialNo = subred.SerialNo == null ? "" : subred.SerialNo,
InspectionDate = subpat.InspectionDate,
NextInspectionDate = s.NextInspectionDate == null ? (DateTime?)null : s.NextInspectionDate,
}).ToList();
but I get al records duplicated.

C#: LINQ not returning the same result as SQL

I'm trying to convert the following SQL query to LINQ, but getting different result count with both,
SQL Query:
SELECT T5.CNTR, T5.BenefitCode,T5.ApprovedFlag,
T5.PaymentFrequencyCode, T5.InstalmentAmt, T5.TotalAmt,
T5.CarRego
FROM
dbo.EmployeeBenefit As T5
LEFT JOIN dbo.Payee ON T5.PayeeCntr = dbo.Payee.CNTR
LEFT JOIN dbo.BankDetails ON dbo.Payee.BankCntr = dbo.BankDetails.BankCntr
Left Join dbo.EmployeeCar As T4 on T5.EmployeeCarCntr=T4.Cntr
Inner Join dbo.EmployeeEntity As T1 On T5.EmployeeEntityCntr=T1.EmployeeEntityCntr
Inner Join dbo.EmployerEntity As T2 On T1.EmployerEntityCntr=T2.EmployerEntityCntr
where T5.EmployeeCntr = 117165
AND ((T5.EndDate is Null) OR (T5.EndDate >= GETDATE()))
LINQ:
var result = (from employeeBenefit in context.EmployeeBenefit
from payee in context.Payee.Where(x => x.Cntr == employeeBenefit.PayeeCntr).DefaultIfEmpty()
from bankDetails in context.BankDetails.Where(x => x.BankCntr == employeeBenefit.PayeeCntr).DefaultIfEmpty()
from employeeCar in context.EmployeeCar.Where(x => x.Cntr == payee.BankCntr).DefaultIfEmpty()
from employeeEntity in context.EmployeeEntity
where employeeEntity.EmployeeEntityCntr == employeeBenefit.EmployeeEntityCntr
from employeeEntity1 in context.EmployeeEntity
where employeeEntity.EmployerEntityCntr == employeeEntity1.EmployerEntityCntr
&& employeeBenefit.EmployeeCntr == iEmployeeID
&& (!employeeBenefit.EndDate.HasValue || employeeBenefit.EndDate >= DateTime.Now)
&& employeeBenefit.EmployeeCntr == 117165
&& employeeBenefit.CarRego == registration
select new
{
CNTR = employeeBenefit.Cntr,
BenefitCode = employeeBenefit.BenefitCode,
PaymentFrequencyCode = employeeBenefit.PaymentFrequencyCode,
InstalmentAmount = employeeBenefit.InstalmentAmt,
TotalAmount = employeeBenefit.TotalAmt,
CarRego = employeeBenefit.CarRego,
ApprovedFlag = employeeBenefit.ApprovedFlag
}).ToList();
Please let me know what i'm missing.
For the data in my database the SQL query is returning 10 records. But, the LINQ is returning 2700 records.
Not a full answer (I'm late for work) but:
var result = (from T5 in context.EmployeeBenefit
join PY in dbo.Payee on T5.PayeeCntr equals PY.CNTR into PY1
where T5.EmployeeCntr = 117165
select new {
CNTR = T5.Cntr,
...
}
).ToList();
It was the issue with the condition mismatch that i had done in the LINQ. The below query just worked fine. Thank you for helping me with the issue.
var result = (from employeeBenefit in context.EmployeeBenefit
from payee in context.Payee.Where(x => x.Cntr == employeeBenefit.PayeeCntr).DefaultIfEmpty()
from bankDetails in context.BankDetails.Where(x => x.BankCntr == payee.BankCntr).DefaultIfEmpty()
from employeeCar in context.EmployeeCar.Where(x => x.Cntr == employeeBenefit.EmployeeCarCntr).DefaultIfEmpty()
join employeeEntity in context.EmployeeEntity
on employeeBenefit.EmployeeEntityCntr equals employeeEntity.EmployeeEntityCntr
join employerEntity in context.EmployerEntity
on employeeEntity.EmployerEntityCntr equals employerEntity.EmployerEntityCntr
where employeeBenefit.EmployeeCntr == 117165 && (!employeeBenefit.EndDate.HasValue || employeeBenefit.EndDate >= DateTime.Now)
select new
{
CNTR = employeeBenefit.Cntr,
BenefitCode = employeeBenefit.BenefitCode,
PaymentFrequencyCode = employeeBenefit.PaymentFrequencyCode,
InstalmentAmount = employeeBenefit.InstalmentAmt,
TotalAmount = employeeBenefit.TotalAmt,
CarRego = employeeBenefit.CarRego,
ApprovedFlag = employeeBenefit.ApprovedFlag
}).ToList();

How to use Left join linq for multiple tables

I'm Stuck at the joining multiple tables.
Context: i have order table which is linked to productTable(name: ORDER_DETAILS) and recipeTable(ORDER_RECIPEs).I can order product from product menu and recipes from recipe menu. and when i click cart btn, then there must be complete list of product orders and recipe order. what am i getting, both orders are merged in single order but i want these as 2 separate rows under single orders. you can see the result in picture.
var data = (from order in orderEntities.ORDERS
join customer in orderEntities.CUSTOMERS on order.FK_CustomerEmail_Orders equals customer.CustomerEmail
join orderDetail in orderEntities.ORDER_DETAILS on order.OrderId equals orderDetail.FK_OrderId_OrderDetails into s
from orderDetail in s.DefaultIfEmpty()
join product in orderEntities.PRODUCTS on orderDetail.FK_ProductId_OrderDetails equals product.ProductId into p
from product in p.DefaultIfEmpty()
join brand in orderEntities.BRANDS on product.FK_BrandId_Products equals brand.BrandId into b
from brand in b.DefaultIfEmpty()
join orderRecipe in orderEntities.ORDER_RECIPE on order.OrderId equals orderRecipe.FK_OrderId_OrderRecipe into ro
from orderRecipe in ro.DefaultIfEmpty()
join recipe in orderEntities.RECIPEs on orderRecipe.FK_RecipeId_OrderRecipe equals recipe.RecipeId into r
from recipe in r.DefaultIfEmpty()
join rBrand in orderEntities.BRANDS on recipe.FK_BrandId_Recipes equals rBrand.BrandId into rb
from rBrand in rb.DefaultIfEmpty()
//into ps from rev in ps.DefaultIfEmpty()
where customer.CustomerEmail == customerEmail && order.OrderStatus == status &&
brandId == 960
//(brand.BrandId == brandId && rBrand.BrandId == brandId)
orderby order.OrderId descending
Select Query
select new
{
Brand = new
{
BrandId = brand == null ? 0 : brand.BrandId,
BrandName = brand == null ? String.Empty : brand.BrandName,
BrandCategory = brand == null ? String.Empty : brand.BrandCategory
},
Customer = new
{
customer.CustomerId,
customer.CustomerEmail,
customer.CustomerFirstName,
customer.CustomerLastName,
customer.CustomerMobile,
customer.CustomerImageUrl
},
OrderDetail = new
{
OrderDetailId = orderDetail != null ? orderDetail.OrderDetailId : 0 ,
OrderDetailQuantity = orderDetail != null ? orderDetail.OrderDetailQuantity: 0.0 ,
OrderDetailTime = orderDetail != null ? orderDetail.OrderDetailPlaceTime : DateTime.Now,
OrderDetailProductId = orderDetail != null ? orderDetail.FK_ProductId_OrderDetails : 0 ,
OrderDetailOrderId = orderDetail != null ? orderDetail.FK_OrderId_OrderDetails : 0
},
OrderRecipe = new
{
OrderRecipeId = orderRecipe != null ? orderRecipe.OrderRecipeId : 0,
orderRecipeQuantity = orderRecipe != null ? orderRecipe.OrderRecipeQuantity : 0,
OrderRecipePlaceTime = orderRecipe != null ? orderRecipe.OrderRecipePlaceTime : DateTime.Now ,
orderRecipeOrderId = orderRecipe != null ? orderRecipe.FK_OrderId_OrderRecipe: 0,
orderRecipeRecipeId = orderRecipe != null ? orderRecipe.FK_RecipeId_OrderRecipe :0
},
Product = new
{
ProductId = product == null ? 0 : product.ProductId,
ProductTitle = product == null ? String.Empty : product.ProductTitle,
ProductOldPrice = product == null ? 0.0 : product.ProductOldPrice,
ProductNewPrice = product == null ? 0.0 : product.ProductNewPrice,
ProductImageUrl = product == null ? String.Empty : product.ProductImageUrl,
ProductContent = product == null ? String.Empty : product.ProductContent,
ProductCategory = product == null ? String.Empty : product.ProductCategory,
ProductSubCategory = product == null ? String.Empty : product.ProductSubCategory,
ProductPostedTime = product == null ? DateTime.Now : product.ProductPostedTime,
ProductStocks = product == null ? String.Empty : product.ProductStocks,
ProductStatus = product == null ? String.Empty : product.ProductStatus,
ProductBrandId = product == null ? 0 : product.FK_BrandId_Products
},
Recipe = new
{
RecipeId = recipe != null ? recipe.RecipeId: 0 ,
RecipeTitle = recipe != null ? recipe.RecipeTitle : String.Empty,
RecipePrice = recipe != null ? recipe.RecipePrice : 0,
RecipeImage = recipe != null ? recipe.RecipeImage: String.Empty,
RecipeCategory = recipe != null ? recipe.RecipeCategory: String.Empty,
RecipePostTime = recipe != null ? recipe.RecipePostTime : DateTime.Now,
RecipeStock = recipe != null ? recipe.RecipeStock: String.Empty,
RecipeStatus = recipe != null ? recipe.RecipeStatus : false,
ProductBrandId = recipe != null ? recipe.FK_BrandId_Recipes: 0
},
order.OrderId,
order.OrderPlaceTime,
order.OrderCompletedTime,
order.OrderStatus,
order.FK_CustomerEmail_Orders
}).Skip(offset).Take(limit).ToList();
I have followed this :
Left Join Linq
you can see here, Products and recipe are combined in same order but if product is there, recipe should be 0 and vice versa. like this:
order:{
brand:{ 10 },OrderRecipe:{ 1 },Recipe{1}, orderDetail:{ 0 },products: {0} orderId: 1 ..},{
brand:{ 10 },OrderRecipe:{ 2 },Recipe{2}, orderDetail:{ 0 },products: {0} orderId: 1 ..},{
brand:{ 10 },orderDetail:{ 1 },products: {1},OrderRecipe:{ 0},Recipe{0} orderId: 1...},{
brand:{ 10 },orderDetail:{ 2 },products: {2},OrderRecipe:{ 0},Recipe{0} orderId: 1...}
If there's any other better way to do this. kindly correct me here.
You will surely get the result like that, because you have joined both tables with your ORDER.
What you can do is:
1) you can make the objects separately like this:
var recipe = (from db.order ...
join orderRecipe in orderEntities.ORDER_RECIPE on order.OrderId equals orderRecipe.FK_OrderId_OrderRecipe into ro
from orderRecipe in ro.DefaultIfEmpty()
join recipe in orderEntities.RECIPEs on orderRecipe.FK_RecipeId_OrderRecipe equals recipe.RecipeId into r
from recipe in r.DefaultIfEmpty()
join rBrand in orderEntities.BRANDS on recipe.FK_BrandId_Recipes equals rBrand.BrandId into rb
from rBrand in rb.DefaultIfEmpty())
and after that you can use both the objects accordingly
2) if you want to use join on both in same query. check your generated sql against linq in visual studio. what you gonna do is use right join for your products and left for your recipes..
i hope this will help you.

How do I optimize this LINQ query? It runs localhost but it doesn't run on Azure

I have this LINQ query and am getting results I need. However it takes 5-6 seconds to show results on localhost, and I can't even run this on Azure.
I'm new to LINQ, and I'm sure that I'm doing something inefficient.
Could someone direct me to optimize?
var joblist = (from t in db.Tracking
group t by t.JobNumber into j
let id = j.Max(x => x.ScanDate)
select new
{
jn = j.Key,
ti = j.FirstOrDefault(y => y.ScanDate == id).TrackingId,
sd = j.FirstOrDefault(y => y.ScanDate == id).ScanDate,
lc = j.FirstOrDefault(y => y.ScanDate == id).LocationId
}).Where(z => z.lc == lid).Where(z => z.jn != null);
jfilter = (from tr in joblist
join lc in db.Location on tr.lc equals lc.LocationId
join lt in db.LocType on lc.LocationType equals lt.LocationType
select new ScanMod
{
TrackingId = tr.ti,
LocationName = lc.LocationName,
JobNumber = tr.jn,
LocationTypeName = lt.LocationTypeName,
ScanDate = tr.sd,
StoneId = ""
}).OrderByDescending(z => z.ScanDate);
UPDATE:
This query runs on Azure(s1) but it takes 30 seconds. This table has 500,000 rows and I assume that OrderByDescending or FirstOrDefault is killing it...
var joblist = db.Tracking
.GroupBy(j => j.JobNumber)
.Select(g => g.OrderByDescending(j => j.ScanDate).FirstOrDefault());
jfilter = (from tr in joblist
join lc in db.Location on tr.LocationId equals lc.LocationId
join lt in db.LocType on lc.LocationType equals lt.LocationType
where tr.LocationId == lid
select new ScanMod
{
TrackingId = tr.TrackingId,
LocationName = lc.LocationName,
JobNumber = tr.JobNumber,
LocationTypeName = lt.LocationTypeName,
ScanDate = tr.ScanDate,
StoneId = ""
}).OrderByDescending(z => z.ScanDate);

Resources