Can I use if clause with Linq where?
for example: I have a table with 4 filed(Id,UserId,Type,Sing).
I want select recorde that userid is 1 and if Type="None" , Sing should True.
(from d in db.Receive
where ((((d.SendType == "None") ? ((d.Signed) ? true : false) : true)) && userid==1)
select d).ToList();
when i use
((d.SendType == "None") ? ((d.Signed) ? true : false) : true)
it is select records that if Type="None" , Sing should True. but when add userid condition , don't return any records.
Isn't it better:
from d in db.Receive
where ((d.SendType == "None" && d.Signed) || d.SendType != "None") && userid == 1)
select d
and so?
(((d.SendType == "None") && (userid == 1)) ? ((d.Signed) ? true : false) : true)
Theres lots of brackets there...if I understand you correctly userid == 1 is used regardless so why not just have
where (((d.SendType == "None" && userid == 1) ? ((d.Signed) ? true : false) : true)))
select d).ToList();
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 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.
I'm busy rewriting a system and are using Linq queries to extract data from the database. I am used to plain old TSQL and stored procedures so my Linq skills are not the best.
I have a sql query that I try to rewrite in Linq that contains a join, where clause and IN statements. I do get it right but when I run the sql query I get a different value as from the Linq query. Somewhere I'm missing something and can't find the reason.
Here is the SQL:
select
isnull(Sum(QtyCC) + Sum(QtyEmployee), 0) *
isnull(Sum(UnitPrice), 0)[TotalRValue]
from
tbl_app_KGCWIssueLines a
inner join tbl_app_KGCWIssue b on b.IssueNrLnk = a.IssueNrLnk
where
b.CreationDate >= '2011-02-01' and
a.IssueNrLnk IN (
select
IssueNrLnk
from
tbl_app_KGCWIssue
where
CustomerCode = 'PRO002' and
ISNULL(Tier1,'') = 'PRO002' and
ISNULL(Tier2,'') = 'HAMD01' and
ISNULL(Tier3,'') = '02' and
ISNULL(Tier4,'') = '02001' and
ISNULL(Tier5,'') = 'PTAHQ001' and
ISNULL(Tier6,'') = '035' and
ISNULL(Tier7,'') = '' and
ISNULL(Tier8,'') = '' and
ISNULL(Tier9,'') = '' and
ISNULL(Tier10,'') = ''
)
And here is the Linq:
ctx.ObjectContext.tbl_app_KGCWIssue
.Join(ctx.ObjectContext.tbl_app_KGCWIssueLines,
i => i.IssueNrLnk, l => l.IssueNrLnk, (i, l) => new { i, l })
.Where(o => o.i.CreationDate >= IntervalStartDate)
.Where(p => ctx.ObjectContext.tbl_app_KGCWIssue
.Where(a =>
a.CustomerCode == CustomerCode &&
a.Tier1 == employee.Tier1 &&
a.Tier2 == employee.Tier2 &&
a.Tier3 == employee.Tier3 &&
a.Tier4 == employee.Tier4 &&
a.Tier5 == employee.Tier5 &&
a.Tier6 == employee.Tier6 &&
a.Tier7 == employee.Tier7 &&
a.Tier8 == employee.Tier8 &&
a.Tier9 == employee.Tier9 &&
a.Tier10 == employee.Tier10)
.Select(i => i.IssueNrLnk)
.Contains(p.l.IssueNrLnk))
.Sum(p => p.l.UnitPrice * (p.l.QtyEmployee + p.l.QtyCC));
I'm trying to get three columns back from the database, DecalExpireDate, DecalExpireMonth and DecalExpireYear. Basically, I'm trying to check if it has a previous expiration date and if it does, I need to get the latest expiration date, as it may have multiple previous expiration dates.
var previousExpirationDate = (from d in db.CT_Decals
where d.TankID == decal.TankID
&& d.DecalStatus == "Approved"
&& d.DecalExpireDate == ((from dn in db.CT_Decals
where dn.TankID == decal.TankID
&& dn.DecalStatus == "Approved"
select dn.DecalExpireDate).Max())
select new
{
d.DecalExpireDate,
d.DecalExpireMonth,
d.DecalExpireYear
});
This query isn't working, can anybody see the problem? I'm searching by TankID, Status = approved and then I try to use the max expirationDate.
How about this
var result = db.CT_Decals.Where(o => o.TankId == decal.TankId && o.DecalStatus == "Approved")
.OrderByDescending(o => o.DecalExpireDate)
.Select(o => new { o.DecalExpireDate,
o.DecalExireMonth,
o.DecalExireYear }).First()
or
var result = (from d in db.CT_Decals
where d.TankID == 1 && d.Status == "Approved"
orderby d.ExpireDate descending
select new { d.DecalExpireDate,
d.DecalExpireMonth,
d.ExpireDate }).First();
The problem it's with the that max function couldn't be translated to Sql in the scope that you need so you could try like this
var previousExpirationDate = (from d in db.CT_Decals
where d.TankID == decal.TankID
&& d.DecalStatus == "Approved"
&& d.DecalExpireDate == ((from dn in db.CT_Decals
where dn.TankID == decal.TankID
&& dn.DecalStatus == "Approved"
order by dn.DecalExpireDate
select dn.DecalExpireDate).First())
select new
{
d.DecalExpireDate,
d.DecalExpireMonth,
d.DecalExpireYear
});
Although Max may be the problem in your example, it would be nice to find a way to use it properly because it is faster than sorting. How about:
Edit: this answer only returns the DecalExpireDate
var previousExpirationDate = (from d in db.CT_Decals
where d.TankID == decal.TankID
&& d.DecalStatus == "Approved"
select new
{
d.DecalExpireDate,
d.DecalExpireMonth,
d.DecalExpireYear
}).Max(d => d.DecalExpireDate);
For this version you will have to test to see if it's worth making an extra call to the database to avoid sorting:
var latestDate = (from d in db.CT_Decals
where d.TankID == decal.TankID
&& d.DecalStatus == "Approved"
select d.DecalExpireDate).Max();
var previousExpirationDate = (from d in db.CT_Decals
where d.TankID == decal.TankID
&& d.DecalStatus == "Approved"
&& d.DecalExpireDate == latestDate
select new
{
d.DecalExpireDate,
d.DecalExpireMonth,
d.DecalExpireYear
}).First();
I am trying to do a search with LINQ to NHibernate.
I have this code:
from d in rep.QueryAll<Document>()
where
d.Plata != null && d.Contractant != null && d.Stadiu == StadiuDocument.Polita
&& (d.NrPolita.Contains(query) ||
d.Contractant.CodUnic.Contains(query) ||
d.Contractant.Denumire.Contains(query) ||
d.Plata.IdTranzactie.Contains(query)) &&
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
select new
{
The problem is that I have some select inputs that have general values. Something like this:
<select id="tippolita" >
<option value = "-1">Any value</option>
<option value = "1">Value 1</option>
<option value = "2">Value 2</option>
<option value = "3">Value 3</option>
</select>
So when "Any value" is selected the where statement should be true like I wrote here:
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
This is almost the same as what I would write in SQL.
An error occurs inside the Nhibernate source code at line 33 in the file "Linq\NHLinqExpression.cs"
_expression = PartialEvaluatingExpressionTreeVisitor.EvaluateIndependentSubtrees(expression);
This error actually comes from the re-linq library.
One obvious workaround is to just write 3 if statements and put the appropriate LINQ queries in each of them but that means writing a lot more code.
Is there any way to make this kind of query work without copy-pasting the entire query and modifying just a little of it?
P.S.
This is the inner exception:
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
at lambda_method(Closure
)
I would rewrite this:
((TipPolita != null) ? (d.Tip == (TipProdus)TipPolita) : (1 == 1)) &&
((StareDocument != null) ? (d.Stare == (StareDocument)StareDocument) : (1 == 1))
as
(TipPolita == null || d.Tip == (TipProdus)TipPolita) &&
(StareDocument == null || d.Stare == (StareDocument)StareDocument)
I don't know whether it'll work in NHibernate or not, but it's more idiomatic C# at least, so I would expect that it's more likely to be supported.
As an alternative, you could just replace "1 == 1" with "true".
Well, figured out how to do this the proper way
var date = rep.QueryAll<Document>().Where(d => d.Plata != null && d.Contractant != null && d.Stadiu == StadiuDocument.Polita);
if (!string.IsNullOrEmpty(query))
date = date.Where(d => (d.NrPolita.Contains(query) ||
d.Contractant.CodUnic.Contains(query) ||
d.Contractant.Denumire.Contains(query)));
I just move the ifs into the code and build the query(or rather the IQueryable) bit by bit