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