I have a model of a game that has a nullable DateTime value:
public class Game
{
[Key]
public int Id { get; set;}
public virtual ICollection<PlayerGames> Players { get; set;}
public DateTime StartTime { get; set; }
public DateTime? EndTime { get; set; }
public int? WinnersTeam { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public DbSet<Game> Games { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options) {}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Game>().ToTable("Game");
modelBuilder.Entity<Game>()
.Property<DateTime?>(m => m.EndTime)
.IsRequired(false)
.ForSqliteHasColumnType("TEXT");
}
}
My program is using Sqlite database which is set up in Startup.cs like that:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
}
Everything is working fine, except I cannot read the value of EndTime property. However when I update it, it is successfully stored in DB.
Notice that DateTime values are stored in Sqlite as TEXT. So for example one of the values stored in DB is "2017-01-06 20:35:44.880908" however program always returns "01/01/0001 00:07:42" when accessing property EndTime.
How to tell EF to parse text from Sqlite to DateTime? in proper format?
Answers to questions:
- The value returned is
nullin case ofnullvalue in database and always "01/01/0001 00:07:42" in case of any other value. I access the value like that:
public Game GetFirstGameEndTime() { var t = _context.Games.First().EndTime; return t; // t in debuger is value either null or "01/01/0001 00:07:42" }