实体框架和System.Data.Sqlite日期时间问题

时间:2012-11-13 08:58:14

标签: entity-framework sqlite datetime system.data.sqlite

我首先将现有的sqlite3数据库(通过system.data.sqlite)与实体框架(版本5)代码映射有问题。

数据库中有一个名为notes的表,我映射到我的实体类:

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更改为string将解决问题,但它给了我相同的异常。我尝试使用DateTime?,同样的错误。

看起来,也许我错了,System.Data.Sqlite试图将该字段转换为datetime(因为名称或其他东西)。

这是我的例外的堆栈跟踪:

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)

有人可以告诉我如何解决这个问题。

2 个答案:

答案 0 :(得分:0)

你需要使用DateTime吗?作为类型

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

这将允许Date字段的空值

答案 1 :(得分:0)