Convert mysql in Linq Lambda - c#

I am trying to convert an expression to lambda, but I can't do it correctly because the result executing it in the database and in the lambda query gives different result.
SQL Query:
select tab1.* from table1 tab1 inner join table2 tab2 on tab1.id = tab2.id
That query gives me 16 rows but I can't make a lambda expression that doesn't return an empty list.
My Lambda expression:
var query = table1.Join(table2, tab1=> tab1.id, tab2=> tab2.id, (tab1, tab2) => new {tab1}).ToList();

Related

Linq Sql Query result is different from the SQL query run in the database

When I run the query in C# code using Linq the result returned is different from the sql query run in sql server
SQL query
SELECT TOP (1000) [Teamid]
,[TeamName]
,[TemplateId]
,[TemplateName]
FROM [MPFT_SendIT].[dbo].[VMTemplate]
where
Teamid=1
Result
SQL Query of the VMTemplate View
SELECT dbo.Team.Id AS Teamid, dbo.Team.TeamName,
dbo.MessageTemplate.Id AS TemplateId,
dbo.MessageTemplate.TemplateName
FROM dbo.Team INNER JOIN
dbo.TemplateLookup ON dbo.Team.Id =
dbo.TemplateLookup.TeamId INNER JOIN
dbo.MessageTemplate ON dbo.TemplateLookup.TemplateId =
dbo.MessageTemplate.Id
where
TeamId= 1
Result
Linq SQL
var teamid = _db.TeamLookups.Where(i => i.UserId == 20).Select(x =>
x.TeamId).ToList(); // teamid return value is 1
ViewBag.messageTemplate = _db.VMTemplates.Where(i =>
teamid.Contains(i.Teamid));
Linq query only returns one record line 1 of the sql query instead of 2 records as expected. Any help on how to solve this issue ?
Why Contains()? You should use equality operator rather
_db.VMTemplates.Where(i => teamid == i.Teamid).ToList();
Per your comment, then your Linq expression should work just fine. Add a ToList() to it
ViewBag.messageTemplate = _db.VMTemplates.Where(i =>
teamid.Contains(i.Teamid)).ToList();

C# Linq Table query to count the non-matching entries

I am quite new to this, I am running two SQL queries and I am creating two separate data tables, DataTable1 and DataTable2.
I am applying some linq criteria to DataTable1 and creating another data table from that, which is DataTable3.
var Query3 = from table1 in DataTable1.AsEnumerable()
where table1.Field<DateTime>("DateTime") <= Yday
where table1.Field<string>("StockCode").Contains("-CA") && !(table1.Field<string>("StockCode").Contains("-CAB")) ||
table1.Field<string>("StockCode").Contains("-CM") ||
table1.Field<string>("StockCode").Contains("-LP")
select table1;
DataTable DataTable3 = Query3.CopyToDataTable()
Now I would write another query to do the following.
Both data tables have a column JobNumber. I would like to query DataTable3 in DataTable 2 to count the rows that have similar JobNumber entries. Below is what I am doing but I am not getting the correct count.
int count = (from table3 in DataTable3.AsEnumerable()
join table2 in DataTable2.AsEnumerable() on table2.Field<string>("JobNumber") equals table3.Field<string>("JobNumber")
where table2.Field<string>("JobNumber") == table3.Field<string>("JobNumber")
select table2).Count();
You are creating a cartesian join and counting its result, was that what you indented ? Also in your linq your Join expression and where expression is same (where is redundant). It is not clear what you really want to count. Probably you instead wanted to count those in DataTable2 where JobNumbers exists in DataTable3?:
var jobNumbers = (from r in DataTable3.AsEnumerable()
select r.Field<string>("JobNumber")).ToList();
var count = (from r in DataTable2.AsEnumerable()
where jobNumbers.Contains( r.Field<string>("JobNumber") )
select r).Count();
As a side note, it would be much easier if you used Linq To SQL instead (rather than Linq To DataSet).

C# Linq query where Table A column is not equal/doesnt math Table B column join

I have an issue with a c# linq query where I use the != operator, it works well in SQL but when I write the same query in C# it returns a different result, which is the correct way to the the results where table a column doesn't match table b column. Please see my sql query below and then my c# query.
SELECT tba.ID,fa.accountnumber,tba.Account_Number,fa.new_legalname,tba.Legal_Name,fa.new_deliverystatusname, fa.new_deliverystatus,tba.Delivery_Charge
FROM [CRM_Embrace_Integration].[dbo].[CRM_Tarsus_Debtors_Accounts] tba
inner join CRM_MBT_GROUP.dbo.FilteredAccount fa
ON fa.accountnumber collate database_default = tba.Account_Number
where fa.new_legalname collate database_default != tba.Legal_Name
and the Linq query looks like this
var sqlJoinQuery = from accCRM in todaysCRMAccounts
join accSQL in todaysCRMViewAccounts
on accCRM.Account_Number equals accSQL.accountnumber
where accCRM.Legal_Name != accSQL.new_legalname
select new { accCRM.Legal_Name, accSQL.new_legalname };
The SQL query returns the correct result as I want where legal_name(table A) is not equals to legal_name(table B) is the other table.
The Linq query return incorrect result, please assist.
I suggest to try the following Linq as you want the data that aren't in table 2:
var result1 = (from m in db1.Table1
select m).ToList();
var result2 = (from m in db2.Table2
select m).ToList();
var finalResult = (from m in result1
where !(from k in result2
select k.Id).Contains(m.Id)
select m).ToList();
The above will return that aren't in Table2. I hope, this is what you wanted.
Your SQL shows you asking for where they are equal. The LINQ shows you asking for when they are not equal.

Performing Subquery using Query Builder in Dataset C#

I'm using this sql statement to produce the desired result. And would like to display those result query in my report in C# using rdlc via Dataset(.xsd).
SELECT pay.Cutoff,
emp.Id,
emp.LastName,
emp.FirstName,
emp.MiddleName,
emp.TinNumber,
job.Rate * 25 AS FixBIR,
(SELECT COUNT(*) AS MonthsWorked
FROM payroll AS pay3
WHERE YEAR(pay3.DateGenerated) = 2014
AND pay3.EmployeeId = 1
AND pay3.Cutoff = 1
ORDER BY MONTH(pay3.DateGenerated) ASC) * (job.Rate * 25)
AS MonthsWorked_FixBIR_TODATE,
pay.TaxWithheld,
(SELECT SUM(payroll2.TaxWithheld) AS TaxTotal
FROM employee AS employee2
INNER JOIN payroll AS payroll2
ON employee2.Id = payroll2.EmployeeId
WHERE (payroll2.Cutoff = 1)
AND (employee2.Id = emp.Id)
AND YEAR(payroll2.DateGenerated) = 2014)
AS Tax_TODATE,
YEAR(pay.DateGenerated) AS YEAR
FROM employee AS emp
INNER JOIN payroll AS pay
ON emp.Id = pay.EmployeeId
INNER JOIN job
ON emp.JobId = job.Id
WHERE pay.Cutoff = 1
AND pay.PayrollMonth = 'August'
AND Year(pay.DateGenerated) = 2014
This statement works fine (tested in navicat).
However, when I transferred this to Dataset using Query Builder it doesn't work. The error says:
The wizard detects the following problems when configuring the TableAdapter: "Fill" Details:
!Generated SELECT statement
Error in SELECT clause: expression near 'SELECT'
Error in SELECT clause: expression near 'FROM'
Missing FROM Clause
Error in SELECT clause: expression near ','.
Unable to parse query text
And if I try to use a simple subquery in the SELECT statement, an error says:
The query cannot be represented graphically in the Diagram and Criteria Pane.
What do I do for me to use the sql statement in rdlc? Are there other ways aside from query builder in dataset?

LinqDataSource: How to assign IQueryable value to where parameters in code

I am trying to assign linq datasource in code behind but I have IQueryable query want to assign in where clouse using Any function like a sub query clause in sql
this is my sql statment
select * from table1 where col1 in (select col1 from table1 where col2 like '%xx%')
how to convert this clouse to bind it into linq datasource code behind
You can convert this query in linq.
var result = from c in db.table1
where db.table1.Any(e => e.col2.Contain("xx"))
select c;
It sounds like you need to call .ToList() on the query that returns IQueryable.

Categories