无法使用.net Core和Entity Framework从sqlite数据库读取可为空的日期时间值

问题描述:

我有一个具有空值 DateTime 的游戏模型:

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");
    }
}

我的程序正在使用Sqlite数据库,该数据库在像这样的Startup.cs:

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")));
}

一切正常,除非我无法读取 EndTime 属性。但是,当我更新它时,它已成功存储在DB中。

Everything is working fine, except I cannot read the value of EndTime property. However when I update it, it is successfully stored in DB.

请注意, DateTime 值以 TEXT 的形式存储在Sqlite中。 >。因此,例如,存储在数据库中的值之一是 2017-01-06 20:35:44.880908,但是程序在访问属性 EndTime 。

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.

如何告诉EF将Sqlite中的文本解析为 DateTime?以正确的格式?

How to tell EF to parse text from Sqlite to DateTime? in proper format?

答案:


  • 返回的值是 null 在数据库中为 null 的情况下,并且在其他任何值的情况下始终为 01/01/0001 00:07:42。

  • 我这样访问值:

  • 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"
}


我发现的解决方案是将.NET Core更新到1.1.0版本并将软件包更新到新版本:

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和其他相关软件包的版本从1.0.1到1.1.0

  2. 将 Microsoft.EntityFrameworkCore.Tools: 1.0.0-preview2-final更改为 Microsoft.EntityFrameworkCore.Tools.DotNet: 1.1.0-preview4-final

现在可空的DateTime已从数据库正确加载

Now nullable DateTime is properly loaded from DB