EFCore FirstOrDefault null DateTime的InvalidFormatException

时间:2018-02-07 21:52:21

标签: c# entity-framework sqlite datetime entity-framework-core

我在我的项目中使用Entity Framework Core(版本1.1.1.0),它正在连接到SQLite数据库。我有一个包含日期和时间值的数据库表,在SQLite中表示为text数据类型,在我的EF对象中,它是DateTime

这个值不应该为null,但我有生产用户显然对此属性具有空值。因此,每当我的应用程序使用FirstOrDefault查询此表时,它都会抛出一个InvalidFormatException,表示"该字符串不是有效的DateTime。"

我希望能够获得我的结果,如果日期值为null,我想将其设置为值并更新SQLite数据库中的该行。

如何在EF Core中检索行而不抛出InvalidFormatException?我尝试DateTimeDateTime?同时将Nullable<DateTime>设置为可空,但这两种方法似乎都不起作用。

这是针对.NET 4.6运行的WPF应用程序,如果这有任何区别

我的对象:

public class MyObject
{
    public int ID { get; set; }
    public string error { get; set; }
    public string error_description { get; set; }
    public string access_token { get; set; }
    public int expires_in { get; set; }
    public string refresh_token { get; set; }
    public string token_type { get; set; }

    public DateTime expirationDate { get; set; } // the offending property
}

1 个答案:

答案 0 :(得分:0)

如果使用DateTime?无法正常工作,我认为NULL不是您的问题。必须有一些既不是NULL也不是DateTime字符串的值。

您可以尝试将列映射到string以查找有问题的值。

var badObjects =
    dbContext.MyObjects.Where(
        o =>
        {
            DateTime value;
            return !DateTime.TryParse(o.expirationDate, out value);
        });
相关问题