Linq query output does not match with Sql query output - sql

Repository.Calls
.Count(call => call.OutcomeActionDate.Value >= fourWeeksStartDate &&
call.OutcomeActionDate.Value < threeWeeksStartDate &&
call.UserId == user.UserId);
Above query gives me output 1 and the sql query:
select *
from calls
where userid = 1006 and
outcomeactiondate >= '2013-08-19' and
OutcomeActionDate < '2013-08-26'
gives me the output 15.
The output 15 is correct. I am not sure why is the linq query giving me incorrect value ?
All the parameter values used in select query are same as passed in the linq query.

Try to use Date part of filtered dates:
Calls.Count(call => call.OutcomeActionDate.Value >= fourWeeksStartDate.Date &&
call.OutcomeActionDate.Value < threeWeeksStartDate.Date &&
call.UserId == user.UserId);

Related

LINQ query where column contains a specific number >= specific value you want to query

I have a table named SubcodeTable and I want to query in SubsidiaryCode where first 3characters is >= to 21Y
Query in table where a column contains >= '21Y'
SubcodeTable:
Column1 Column2
SubsidiaryCode Desc
18Y-001 AAA
19Y-001 AAA
20Y-001 AAA
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
So output should display:
Column1 Column2
SubsidiaryCode Desc
21Y-001 CCC
22Y-003 EEE
23Y-001 FF
By the way first 3 characters of SubsidiaryCode represent year like 21Y=2021.
I manage to create a SQL query, so how do to it in LINQ query ?
SQL query:
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '21'
ORDER BY Whh_SubsidiaryCode
So this is my LINQ query, I tried to use y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says Too many characters in car literal & operator > cannot be applied to operands of type string and char.
private List<string> GetBudgetCodes()
{
using (var ctx = LinqExtensions.GetDataContext<NXpert.FixedAsset.DataAccess.FixedAssetDataContext>("AccountingDB"))
{
var list = (from x in ctx.DataContext.E_WHDetailEntries
join y in ctx.DataContext.E_WHHeaderEntries
on x.Whd_WHNo equals y.Whh_WHNo
where x.Whd_StockType == "FS2"
&& y.Whh_SubsidiaryCode.Contains("y")
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
select new { y.Whh_SubsidiaryCode }
).DistinctBy(y => y.Whh_SubsidiaryCode).OrderBy(y => y.Whh_SubsidiaryCode).ToList();
var budgetcode = list.Select(y => y.Whh_SubsidiaryCode.Trim()).ToList();
return budgetcode;
}
}
As it says in exception
> cannot be applied to operands of type string and char.
You need to parse Whh_SubsidiaryCode first to be able to compare values.
So this
&& y.Whh_SubsidiaryCode.Substring(0,2) >= '21'
should be like this:
&& Convert.ToInt32(y.Whh_SubsidiaryCode.Substring(0,2)) > 21
y.Whh_SubsidiaryCode.Substring(0,2) >'20' but it says
Too many characters in char literal
Indeed; you can only put one character inside ' in C#. If you want to put more than one character, you need a string, which is delimited by "
Operator > cannot be applied to operands of type string and char
> as a maths operation doesn't work with a string on one side and a char on the other. You can use it on two chars, or on two strings, but not on a mix
'a' > 'b' //false
"a" > "b" //false
"a" > "A" //true - a is ASCII 97, A is ASCII 65. 97 is greater than 65
I'd say you can simply use:
y.Whh_SubsidiaryCode >= "21Y"
if your code is always number number Y, but you should be aware that this is an alphameric comparison. It'll work fine for any other code that is also number number Y. Critically, a string of 100Y is not greater than 21Y because the first character, 1 is not greater than 2
Unless you have other codes like 21X, you can dump the LIKE '%Y%' / Contains("y") - that just slows things down
I finally gotten a solution in SQL.
by using LEN then get the length then using LEFT to get the first 2 char.
Then create a where clause for the condition:
LEFT(Whh_SubsidiaryCode,2) >= '20'
SELECT LEN (Whh_SubsidiaryCode) [StringLength],LEFT(Whh_SubsidiaryCode,2)[FirsttwoCharInSubCode]
,Whd_WHNo [RR NUMBER], Whh_SubsidiaryCode [SubsidiaryCode], Whd_WHSeqNo [SEQ], Whd_WHSplitSeqNo [SPLIT SEQ] ,Whd_WHIssuedQty [QTY],Saw_StockName [ITEM NAME],Saw_StockSpecs1 [ASSET DESCRIPTION]
FROM E_WHDetailEntry
JOIN E_WHHeaderEntry ON Whd_WHNo=Whh_WHNo
JOIN E_StockAndWorkMaster ON Whd_StockCode=Saw_StockCode
WHERE Whd_StockType='FS2'
AND Whh_SubsidiaryCode LIKE '%Y%' AND LEFT(Whh_SubsidiaryCode,2) >= '20'
ORDER BY Whh_SubsidiaryCode
Thanks for the help guys.
About the LINQ I manage to query the results using List, create a function that returns the met condition.
Code:
private static bool CodeFiltered(string code)
{
return ((Convert.ToInt32(code.Substring(0,2)) >= 20));
}
var lstBudgetCodes = GetBudgetCodes();
List<string> ResultCode =new List<string>(lstBudgetCodes.FindAll(CodeFiltered));

how to convert a sql having sub query in the from clause into Linq?

I have a sql statement as below, I want to translate it into Linq
select *
from
(
select Top 12 *
from DailyData
where ddaCode = '600000' and ddaDate < '2008/12/31'
order by ddaDate desc) as X
order by ddaDate
How can I do it? Thank you.
The From subquery becomes your first Linq query. Then this is queried in the second one.
var fromResults = DailyData.Where(x => x.ddaCode == "600000"
&& x.ddaDate < new DateTime(2008,12,31)
.OrderByDescending(x => x.ddaDate)
.Take(12);
var results = fromResults.OrderBy(x => x.ddaDate)

How to change the following SQL query to a Linq query

How to change the following SQL query to Linq query and how to convert results to a list of strings?
select Name
from Categories
where ID in (select CID from CategoryLink where VID = 57)
Please, provide some extra context. From the fist sight the code should be something like this:
List<string> names = db.Categories
.Where(c => db.CategoryLink.Any(cl=>cl.VID == 57 && CID == c.ID))
.ToList();

Performance issue with SQL server due to sql query

Need some help to solve this error:
The query processor ran out of internal resources and could not
produce a query plan. This is a rare event and only expected for
extremely complex queries or queries that reference a very large
number of tables or partitions. Please simplify the query. If you
believe you have received this message in error, contact Customer
Support Services for more information.
SQL query: (I am just putting one of the query. I got 9 such queries running)
var query1 = from article in _db.Articles
from scl in article.Scls
where article.publishDate < DateTime.Now
&& article.removalDate > DateTime.Now
&& article.finished == true
&& article.flagged== true
&& listOfScl.Contains(scl.id)
select article;
var query2 = from article in _db.Articles
from com in article.Coms
where article.publishDate < DateTime.Now
&& article.removalDate > DateTime.Now
&& article.finished == true
&& article.flagged== true
&& listOfCom.Contains(com.id)
select article;
query = (query1.Union(query2)).Distinct();
Don't know what is wrong with query its working fine but giving some performance issue on SQL Server.
I need some help to avoid such error and re-write this SQL query without using UNION.
Thanks in advance.
Also note that by default LINQ does UNION, which will eliminate duplicates, therefore there is no need for Distinct, which will likely improve performance.
"re-write this SQL query without using UNION.". How is this?
var query1 = from article in _db.Articles
from scl in article.Scls
where article.publishDate < DateTime.Now
&& article.removalDate > DateTime.Now
&& article.finished == true
&& article.flagged== true
&& (
listOfScl.Contains(scl.id)
|| listOfCom.Contains(com.id)
)
select article;
You could try the performance of this, so that you don't need a distinct. It will involve a subquery though, so it's hard to say what will perform better without testing:
var query1 = _db.Articles.Where(article => article.publishDate < DateTime.Now
&& article.removalDate > DateTime.Now
&& article.finished == true
&& article.flagged== true
&& ( article.Scls.Any(s=> listOfScl.Contains(s.id))
|| article.Coms.Any(c=> listOfCom.Contains(c.id))
)
);

Where is the "LEFT" operator in LINQ?

Using SQL Server 2005 I've run a query like this
SELECT *
FROM mytable
WHERE (LEFT (title, 1) BETWEEN #PREFIXFROM AND #PREFIXTO)
I use this to do alphabet filtering, so for example
PREFIXFROM = a
PREFIXTO = c
and I get all the items in mytable between a and c (inclusive)
How do I do this in linq?
Selecting all the records fine.. but
1) how do I do the "LEFT" operation
and 2) How do I do a <= type operator with a non numeric field?
Any ideas appreciated!
Don't think of the SQL - think of what you're trying to achieve, and how you'd do it in .NET. So you're trying to get the first character, and work out whether it's between 'a' and 'c':
var query = from row in mytable
where row.title[0] >= 'a' && row.title[0] <= 'c'
select row;
or in dot notation:
var query = mytable.Where(row => row.title[0] >= 'a' && row.title[0] <= 'c');
Alternatively:
var query = mytable.Where(row => row.title.Substring(0, 1).CompareTo("a") >= 0 &&
row.title.Substring(0, 1).CompareTo("c") <= 0));