2010-12-03 43 views
1

LINQ to Entity Framework 4.0。 SQL Server。實體4.0 Casting Value As DateTime

我想返回對象的列表,並在數據庫中的一列是varchar(255)幷包含日期。我試圖將這個值轉換爲datetime,但是我還沒有找到解決方案。

例子:

List<MyObject> objects = (from c in context.my_table 
           where c.field_id == 10 
           select new MyObject() 
           { 
            MyDate = c.value // This is varchar, want it to be datetime 
           }).ToList(); 

這是不可能的?

更新。這是LINQ to Entity。當試圖轉換爲DateTime我得到:

LINQ to Entities does not recognize the method 'System.DateTime ToDateTime(System.String)' method, and this method cannot be translated into a store expression. 

回答

1

答案是目前不可能使用實體框架。有了LINQ本身,它只是不受實體框架的支持。

0

你想DateTime.Parse(c.value),這將包含日期的字符串,並創建一個DateTime對象出來。

+2

我得到這個錯誤:LINQ到實體無法識別方法「System.DateTime的解析(System.String)」的方法,而且這種方法不能翻譯成商店表達。 – GregInWI2 2010-12-03 19:38:34

0

你可以像這樣 日期= DateTime.Parse(文本)

0

read,而最好的選擇是使用你的結果,然後轉換爲日期時間。像下面一樣,

static void Main(string[] args) 
    { 
     Console.WriteLine(getme()); 
     Console.ReadLine(); 
    } 
    private static DateTime getme() 
    { 
     List<string> ss = new List<string>(); 
     ss.Add("11/11/2010"); 
     var r = from l in ss 
       select new { date = Convert.ToDateTime(l) }; 



     return r.FirstOrDefault().date; 

    } 
+0

這是實體框架。我從SQL Server返回數據。這個版本4.0。轉換不起作用,給我一個錯誤。我用錯誤消息更新了我的問題。 – GregInWI2 2010-12-03 19:45:02

0

你可以轉換爲列表,然後應用轉換...不利的一面是當你調用.ToList()這將帶來所有數據從數據庫,然後在主機端而不是數據庫端進行轉換。在這種情況下可以,但在其他情況下,您將此轉換用於過濾器將會很昂貴。 這裏修改後的樣本:

List<MyObject> objects = (from c in context.my_table 
          where c.field_id == 10).ToList(). 
          Select(c=>new MyObject() 
          { 
           MyDate = Convert.ToDateTime(c.value) 
          }).ToList(); 

博客:http://jaider.net