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.
Related
I want to return a customer which is in this city and buy ItemID = 1, 2 or NULL
List<int?> AcceptableValues = new List<int?>
{
1,2
};
List<Customer> Customers = ListOfCustomer.Where(x => x.CountryTbl.City == 1
&& x.ItemTbl.Any(p => p.ItemID == 1 || p.ItemID ==2 || p.Item is null)
&& x.SellTbl.SellType == 10).ToList();
Is there any way we can use LINQ to filter the customer who only buys itemID in the AcceptableValues ?
I've tried with ItemTbl.SingleOrDefault, or ItemTbl.Where, or AppeptableValues.Contains(m => m.ItemID) but didn't work.
List<Customer> Customers = ListOfCustomer
.Where(c => c.CountryTbl.City == 1
&& c.ItemTbl.Any(i => i.ItemID == null || AcceptableValues.Contains(i.ItemID))
&& c.SellTbl.SellType == 10).ToList();
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.
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
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();
I am trying to perform left outer join on 2 data tables and getting an error : Object reference not set to an instance of an object.
My Code is :
var result =
from dataRows1 in dtInv.AsEnumerable()
join dataRows2 in dtSal.AsEnumerable()
on dataRows1.Field<string>("taken_by").ToUpper() == null ? "" : dataRows1.Field<string>("taken_by").ToUpper()
equals dataRows2.Field<string>("taken_by").ToUpper() == null ? "" : dataRows2.Field<string>("taken_by").ToUpper() into lj
from r in lj.DefaultIfEmpty()
select dtResult.LoadDataRow(new object[]
{
dataRows1.Field<string>("taken_by") == null ? "": dataRows1.Field<string>("taken_by"),
dataRows1.Field<int>("TotalInv") == null ? 0 : dataRows1.Field<int>("TotalInv"),
dataRows1.Field<double>("TotalAmt") == null ? 0.00 : dataRows1.Field<double>("TotalAmt"),
r == null ? 0 : r.Field<int>("TotalSal"),
r == null ? 0 : r.Field<double>("SalAmt")
}, false);