Cannot read nullable datetime value from sqlite db using .net core and Entity Framework

↘锁芯ラ 提交于 2020-01-17 03:36:15

问题


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 null in case of null value 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"
    }
    

回答1:


The solution I found was to just update .NET Core to version 1.1.0 and update packages to new versions:

  1. Microsoft.NETCore.App, Microsoft.EntityFrameworkCore.Sqlite and other related packages version from 1.0.1 to 1.1.0
  2. Change "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" to "Microsoft.EntityFrameworkCore.Tools.DotNet": "1.1.0-preview4-final"

Now nullable DateTime is properly loaded from DB




回答2:


I had similiar issue with my MS SQL DB and to avoid it I had to first check if the variable wasn't DBNull.Value. If it was than I simply assigned the normal null to it.



来源:https://stackoverflow.com/questions/41516093/cannot-read-nullable-datetime-value-from-sqlite-db-using-net-core-and-entity-fr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!