Actually I think I might have fixed it, gonna do some testing, I wll post my solution if it works.
I am migrating an older DB system over to LINQ, I'm having trouble converting a few of the SQL statements though:
SELECT * FROM cities
INNER JOIN deals ON cities.cityId = deals.CityID
INNER JOIN countries ON cities.countryID = countries.CountryId
WHERE deals.endDate >= (someDate)
AND countries.CountryId = (1)
AND deals.soldout = (false)
I've done some research, but I can't get it to work. Here is the LINQ statement I came up with:
var deals = from d in db.deals
join city in db.cities on d.CityID equals city.cityId
join country in db.countries on city.countryID equals country.CountryId
where d.endDate > DateTime.Today && country.CountryId == 1 && d.soldOut == false
select d;
Is there some particular way to use 2 joins in LINQ?
Sorry, I had a formatting error: the statement is meant to select all the deals that have a city who's countryID = 1
You do not need the 2nd join if you have a country code for the city...
var deals = from d in db.deals
join city in db.cities on d.CityID equals city.cityId
where d.endDate > DateTime.Today &&
city.CountryId == 1 && d.soldOut == false
select d;
If you want columns from all tables involved, you can use an anonymous type for that.
select new {d, city, country}
Related
I have two related tables Ticket and Status.
Every ticket can be multiple status. (Open, assigned, closed). But I want all tickets but only one status (newest date) to show.
I could handle with this query on t-sql;
SELECT d.ticketID, statusName, c.statusDate, c.assignedTo,c.statusID
FROM Ticket d LEFT JOIN Status c ON c.ticketID = d.ticketID
WHERE c.statusID = (
SELECT MAX(statusID)
FROM Status c2
WHERE c2.ticketID = d.ticketID)
This is my Linq :
var result = from t in db.Ticket
join s in db.Status.OrderByDescending(x=>x.statusDate).Take(1)
on t.ticketID equals s.ticketID join c in db.Customer
on t.customerID equals c.customerID
But this only returning one row.
I solve my problem with linqer application via converting my Tsql query to linq
from s in db.Status
where s.statusID ==
(from c2 in db.Status where
c2.ticketID == s.Ticket.ticketID &&
c2.statusName == "New" ||
c2.statusName == "Assigned"
select new
{
c2.statusID
}).Max(p => p.statusID)
Thanks for everyone.
Try changing your original linq logic to:
var result = from t in db.Ticket
join s in db.Status on t.ticketID equals s.ticketID into sGroup
from s in sGroup.OrderByDescending(x=>x.statusDate).Take(1)
join c in db.Customer
on t.customerID equals c.customerID
I'm trying to translate following T-SQL query into LINQ:
SELECT * FROM table_A JOIN table_B ON table_A.key = table_B.key AND
table_A.Trouble <> table_B.Trouble
Stackoverflow is full with similar questions, but in my case there are two conditions but each of them has different operator ("equals to" and "not equals to"). Is there any way to get the same result using LINQ?
You can't use the join syntax, you have to use a where clause to connect the two
var query = from a in table_A
from b in table_B
where a.key = b.key &&
a.Trouble != b.Trouble
select new { a, b };
You can also write this query. It should be work fast
var query = from a in table_A
from b in table_B.where(x=>x.key==a.key && x.Trouble != a.Trouble)
select new { a, b };
Really odd issue that I cant work out.
I am trying to join two tables in a linq statement to only retrieve records where the record in table 1 has no related rows in table 2.
I have used Joins before but for some reason I cant get VS to recognise the second table in the linq statement.
EG.
var result =
(from pc in _dataSource.Payments
join bc in _dataSource.BouncedCheques
on pc.PaymentID != bc.PaymentID //This is where the error occurs, VS does not recognise "bc"
where pc.CustomerNumber == getAccountNumber
& pc.IsDeleted == false
orderby pc.PaymentDate descending
select new PaymentAllocation
{
PaymentId = pc.PaymentID,
PaymentDate = pc.PaymentDate,
CustomerNumber = pc.CustomerNumber,
ChequeReference = pc.ChequeReference,
PaymentValue = pc.PaymentValue,
AllocatedValue = pc.AllocatedValue,
UnallocatedValue = pc.PaymentValue - pc.AllocatedValue,
ReceivedBy = pc.ReceivedBy,
PaymentType = pc.PaymentType,
PostedDate = pc.PostedDate
});
Basically the problem is that the variable "bc" does not seem to be recognised, however I have several other similar Linq queries that all work well
Any ideas?
Your problem is that the syntax for join uses the keyword equals and not standard boolean operators.
Try replacing your join by a cartesian product of your tables:
from pc in _dataSource.Payments
from bc in _dataSource.BouncedCheques
where
pc.PaymentID != bc.PaymentID
&& pc.CustomerNumber == getAccountNumber
& pc.IsDeleted == false
In the join clause you should use the equals keyword:
try:
on pc.PaymentID equals bc.PaymentID
I am trying to execute the following SQL statement using linq:
SELECT TTT.SomeField
FROM Table1 as T, Table2 as TT, Table3 as TTT
WHERE (T.NumberID = 100 OR T.NumberID = 101)
AND T.QuestionID = 200
AND T.ResponseID = TT.ResponseID
AND TT.AnswerID = TTT.AnswerID
Essentially getting one field from a third table based on primary/foreign key relationships to the other 2 tables. It is expected to have a single result every time.
var query = from t in db.Table1
join tt in db.Table2 on t.ResponseID equals tt.ResponseID
join ttt in db.Table3 on tt.AnswerID equals ttt.AnswerID
where (t.NumberID == 100 || t.NumberID == 101) && t.QuestionID == 200
select ttt.SomeField
If you always expect single result, you can wrap this in ().Single(), or, if there might be no results found, in ().SingleOrDefault().
If I understand you correct. You should read something about Joins I guess.
here
I've got this stored procedure I'd like to convert to LINQ to SQL, but I'm having a bit of trouble because I'm new to LINQ (and actually, I'm no SQL guru) and I am not getting the expected results. (I tried calling the SPROC from LINQ to SQL but when I send in the Period datetime as parameter on the SPROC I get some error on L2S about the parameter being nullable but I sent it also non-nullable and I still get the same error.) Below is the SQL:
SELECT Persons.IDPerson,Persons.Name,Persons.PaternalName,Departments.DepartmentName,Jobs.Title, Persons.HireDate, Terminations.TerminationDate, Terminations.HireDate
FROM Persons left outer join Terminations on Persons.IDPerson = Terminations.IDPerson
left outer join Departments on Departments.idDepartment = Persons.IdDepartment
left outer join Jobs on Jobs.IDJob = Persons.IDJob
WHERE (Terminations.IDTermination is null OR Terminations.TerminationDate >= #Period)
and Terminations.HireDate <= #Period OR Persons.HireDate <=#Period
ORDER BY Persons.HireDate, Terminations.HireDate asc
This is my LINQ code so far (it does compile but it doesn't give me the records I expect) The Criteria.Period is a nullable datetime:
result = from emp in HRSystemDB.Persons.OfType<Employee>()
join term in HRSystemDB.Terminations on emp.IDPerson equals term.IDPerson into all
from aHire in all.Where(t => (t.IDTermination == null || t.TerminationDate.Date >= Criteria.Period.Value.Date)
&& t.HireDate.Value.Date <= Criteria.Period.Value.Date
|| emp.HireDate.Date <= Criteria.Period.Value.Date).DefaultIfEmpty()
select new DepartmentHeadCountQuery
{
FullName = emp.Name + " " + emp.PaternalName,
Department = emp.Department.DepartmentName,
JobTitle = emp.Job.Title,
TermDate = aHire.TerminationDate,
EHiredDate = emp.HireDate,
TermHireDate = aHire.TerminationDate
};
Thanks in advance.
This (free only for trial) can be usefull: http://www.sqltolinq.com/
Linqer is a SQL to LINQ converter tool.
It will help you to learn LINQ and convert your existing SQL statements.
Not every SQL statement can be converted to LINQ, but Linqer covers many different types of SQL expressions.
Linqer supports both .NET languages C# and Visual Basic.
And a totally free tool:
http://www.linqpad.net/
LINQPad is also a great way to learn LINQ: it comes preloaded with 200 examples from the book, C# 3.0 in a Nutshell. There's no better way to experience the coolness of LINQ and functional programming.
I know this question it's old, but I think it's need a correct answer, I get to this questing searching for a LINQ equivalent of the IN SQL Keyword and see that the equivalent LINQ code for this query are not provided, maybe the Original author answer this question some time ago, but I leave this for other people searching in the internet:
I got to answers one if you like to have Left Outer Joins:
var query = from emp in context.Persons
join ter in context.Terminations on emp.Id equals ter.IdPerson into terminations
join dep in context.Departments on emp.IdDeparment equals dep.IdDepartment into departments
join job in context.Jobs on emp.IdJob equals job.IdJob into jobs
from ter in terminations.DefaultIfEmpty() //Does an Left Outer Join
from dep in departments.DefaultIfEmpty()
from job in jobs.DefaultIfEmpty()
where (ter.IdTermination == null || ter.TerminationDate >= period)
&& (ter.HireDate <= period || emp.HireDate <=period)
select new
{
emp.Id,
emp.Name,
emp.PaternalName,
dep.DepartmentName,
job.Title,
emp.HireDate,
ter.TerminationDate,
TerminationHireDate=ter.HireDate
};
one using Inner Joins
var query = from emp in context.Persons
join ter in context.Terminations on emp.Id equals ter.IdPerson
join dep in context.Departments on emp.IdDeparment equals dep.IdDepartment
join job in context.Jobs on emp.IdJob equals job.IdJob
where (ter.IdTermination == null || ter.TerminationDate >= period)
&& (ter.HireDate <= period || emp.HireDate <=period)
select new
{
emp.Id,
emp.Name,
emp.PaternalName,
dep.DepartmentName,
job.Title,
emp.HireDate,
ter.TerminationDate,
TerminationHireDate=ter.HireDate
};
the variable context is the Linq to SQL or Linq to Entity Context