Linked Questions

Popular Questions

I use Entity Framework to read a SQLite database from a C# console app.

Here is the problem : I have many columns that contains empty string (eg : '') and are mapped to a DateTime property in C#.

When I try to read those records here is the error I got :

Innermost exception System.FormatException : String '' was not recognized as a valid DateTime. at System.DateTimeParse.Parse(ReadOnlySpan`1 s, DateTimeFormatInfo dtfi, DateTimeStyles styles) at Microsoft.Data.Sqlite.SqliteValueReader.GetDateTime(Int32 ordinal)

Mapping the column to a nullable DateTime does not solve the problem.

Obvious solution is to clean up ALL those empty strings and replace them by NULL values. This is not trivial in my case and I cannot guarantee there won't be any other string empty values in the future.

Surprisingly, if a column mapped to an integer contains a empty string value, it works (value is mapped to '0').

Is there a way to ignore those empty string values when mapping to a DateTime ? (eg : it will return a null date or DateTime.MinValue). Note : I use ISO 8601 format not ticks.

EDIT : Here is my code

public class FooContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder builder) {     
           builder.UseSqlite("Data Source=Database.db");
    }

    public DbSet<Bar> Bar { get; set; }
}

public class Bar
{
    public int ID { get; set; }
    public DateTime? SomeDate { get; set; }
}

using(FooContext context = new FooContext())
{                
    var bar = context.Find<Bar>(id); //throw exception
} 

Related Questions