2016-12-29 108 views
0

我有一個sql這樣的查詢:SQL到LINQ轉換失敗

select attendance.intime, attendance.outtime, attendance.date, employees.name from employees left join attendance on employees.id = attendance.employeeid where attendance.date = '12/12/2016' 

我想將其轉換爲LINQ方法的語法。我試過這個。

var attendances = db.Attendances.Include(a => a.Admin).Include(a => a.Employee); 
var employees = db.Employees.Include(a => a.Admin); 

var linq_query = attendances 
       .Join(
        employees, 
        a => a.EmployeeId, 
        e => e.Id, 
        (a, e) => new { e.Name, a.InTime, a.OutTime, a.Date         
       }) 
       .Where(e=> e.Date == DateTime.Parse("12/12/2016")); 

但它給我500內部服務器錯誤。在哪裏改變?

+3

500錯誤可能是很多很多事情。你有調試器的'InnerException'嗎? – G0dsquad

+0

通過刪除'.Where()',不顯示500內部錯誤。而且它也是'INNER JOIN'而不是'LEFT JOIN'的結果.. –

+1

如果你知道日期,爲什麼不使用實際的DateTime對象而不是解析?例如使用'new DateTime(2016,12,12)'。否則,你肯定會遇到解析錯誤 - 在你的服務器的語言環境*中寫入12月13日的正確方法是什麼? –

回答

2

試試這個。

var result = from e in db.Employees 
     join a1 in db.Atendances on e.Id equals a1.EmployeeId into g1 
     where a1.Date == new DateTime(2016, 12, 12) 
     from a in g1.DefaultIfEmpty() 
     select new { 
      a.intime, 
      a.outtime, 
      a.date, 
      e.name 
     }; 
+0

'where a1.Date = new DateTime(2016,12,12)'給調試錯誤。 'a1在當前上下文中不存在' –