2016-03-29 157 views
3

我必須使用「轉換爲日期時間」的方法來比較和參考月份和年份的日期時間,如下LINQ到實體無法識別方法ToDateTime(System.String)

var res = db.Table1 
//other tables, and where conditions 
.Select(x => new MyObj 
{ 
     //... 
     Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(Convert.ToDateTime("01/" + x.month + "/" + x.year), 1))).Description 
}) 

我知道Convert.ToDateTime無法從提供者的SQL中轉換,我需要一個想法來執行該查詢。

更新:我不會在轉換之前實現查詢,因爲這顯然意味着需要所有記錄。

+2

'Convert.ToDateTime'方式無法轉換爲T-SQL,Linq to Entities無法識別它。看看這個答案:http://stackoverflow.com/a/34061692/2946329 –

+0

@ S.Akbari是的我知道,但我需要一個解決方法或類似的東西 – DevT

+1

[LINQ to Entities可能重複無法識別方法'System.DateTime ToDateTime(System.String)'方法](http://stackoverflow.com/questions/20797158/linq-to-entities-does-not-recognize-the-method-system-datetime-todatetimesyste) – Alberto

回答

4

我想我找到做

var res = db.Table1 
//other tables, and where conditions 
.Select(x => new MyObj 
{ 
     //... 
     Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(System.Data.Entity.DbFunctions.CreateDateTime(x.year, x.month, 1, 0, 0, 0), 1)).Description 
}) 
1

這是一個有點粗糙,但你解析日期之前,你可以兌現的SQL查詢列表:

var res = db.Table1.ToList() 
//other tables, and where conditions 
.Select(x => new MyObj 
{ 
//... 
    Imp = x.MyTable.FirstOrDefault(y => y.date_val >= System.Data.Entity.DbFunctions.AddMonths(DateTime.Parse("01/" + x.month + "/" + x.year))).Description 
}) 
+0

如果可能,我不會實現查詢。 – DevT

相關問題