views:

78

answers:

1

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.

+2  A: 

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.
Cristian Boariu
Thanks for your answer. I knew about LINQPad but I guess I'll give it a try.
jasonco