2012-11-13 35 views
4

我有一個問題先映射現有的sqlite3數據庫(通過system.data.sqlite)與實體框架(版本5)的代碼。實體框架和System.Data.Sqlite日期時間問題

有一個在數據庫中調用的筆記,我映射到我的實體類的表:

public class Note 
{ 
    [Column("ZNAME") 
    public string Name { get; set; } 

    [Column("ZDATE")] 
    public DateTime Date { get; set; } 

    [Column("ZNOTE")] 
    public string Description { get; set; } 
} 

在數據庫中,比如我有2行,一有ZDATE字段爲空,其他有一些日期(例如:30/12/1899 21:00:05)。 當我單元測試它,並試圖獲得整個集合或第一行的空日期時間字段時,我得到臭名昭着的異常:「字符串未被識別爲有效的日期時間。」試圖獲得其他行(與日期),我的測試通過。

起初我以爲將DateTime更改爲字符串將解決問題,但它給了我同樣的例外。我試過使用DateTime ?,同樣的錯誤。

它看起來像,也許我錯了,System.Data.Sqlite試圖將該字段轉換爲日期時間(由於名稱或其他)。

這是我的異常堆棧跟蹤:

at System.DateTimeParse.ParseExactMultiple(String s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style) 
    at System.DateTime.ParseExact(String s, String[] formats, IFormatProvider provider, DateTimeStyles style) 
    at System.Data.SQLite.SQLiteConvert.ToDateTime(String dateText, SQLiteDateFormats format, DateTimeKind kind) 
    at System.Data.SQLite.SQLiteConvert.ToDateTime(String dateText) 
    at System.Data.SQLite.SQLiteConvert.ToDateTime(IntPtr ptr, Int32 len) 
    at System.Data.SQLite.SQLite3.GetDateTime(SQLiteStatement stmt, Int32 index) 
    at System.Data.SQLite.SQLite3.GetValue(SQLiteStatement stmt, Int32 index, SQLiteType typ) 
    at System.Data.SQLite.SQLiteDataReader.GetValue(Int32 i) 
    at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetUntypedValueDefault(DbDataReader reader, Int32 ordinal) 
    at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) 
    at System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName) 
    at lambda_method(Closure , Shaper) 
    at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) 
    at lambda_method(Closure , Shaper) 
    at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) 
    at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext() 
    at System.Linq.Enumerable.First[TSource](IEnumerable`1 source) 

能有人給我一些見解如何解決這個問題。

+0

你在連接字符串中有正確的'DateTimeFormat'嗎? –

+0

試過了,沒幫忙... – Redbull

+0

@Redbull你修好了嗎? – qakmak

回答

0

您需要使用DateTime嗎?作爲類型

[Column("ZDATE")] 
public DateTime? Date { get; set; } 

這將使日期字段

+0

我已經試過了,它給出了同樣的錯誤。 – Redbull

+0

如果它仍然給你一個錯誤,那麼恐怕我不能幫忙,但是你必須使用一個可以爲空的DateTime字段。一個空的字符串/空值永遠不會映射到日期時間,並會一直給出錯誤。 – NoPyGod

+0

您是否發現問題所在? – NoPyGod

0

在SQLite的,dates must have the format yyyy-mm-dd空值。

+0

他們可以有更多的格式,因爲這是正常閱讀(11/11/2011),但這不是問題。 我正在使用現有的數據庫,其中一些ZDATE字段爲空(至少sqliteadmin應用程序顯示它們爲空),並且我不能更改該... – Redbull