为什么 EF Core SQLite 返回错误的 int 值?

问题描述 投票:0回答:1

背景

我有一个应用程序写入 SQLite 数据库,该数据库创建了重复记录。我正在创建一个命令提示符工具,该工具读取数据库并输出与重复记录相关的数据。

我使用 EF Core 连接到 SQLite 数据库,当我查询表中的所有记录时,每行的

itemID
属性都是 1。当我在 外部工具 中打开数据库时,值会按预期显示,并带有增量 ID。

IEnumerable 实际结果可视化工具:

IEnumerable visualizer of actual result showing all 1s

使用外部工具的数据源中显示的预期结果

enter image description here

技术

  • .NET 8.0.2
  • Microsoft.EntityFrameworkCore.SqlServer
  • 读取使用 SQLite-NET-PCL 1.8.116 创建的 .db3
  • Visual Studio 2022 - 17.9.1
CREATE TABLE "DefectReportAnswer" 
(
    "Report_id" varchar,
    "Item_id" integer,
    "Note" varchar,
    "Start_date" bigint,
    "End_date" bigint,
    "Defective" integer 
)

代码-模型类:

public class DefectReportAnswer
{
    [Key]
    public string Report_id { get; set; }

    public int Item_id { get; set; }
    public string? Note { get; set; }

    public System.DateTimeOffset Start_date { get; set; }
    public System.DateTimeOffset End_date { get; set; }

    public bool Defective { get; set; }
}

背景:

internal class SQLiteDefectReportContext : DbContext
{
    public SQLiteDefectReportContext(string dbPath)
    {
        DbPath = dbPath;
    }

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

    public string DbPath { get; private set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        optionsBuilder.UseSqlite($"Data Source={DbPath}");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<DefectReportAnswer>()
            .Property(d => d.Start_date)
            .HasConversion(
                d => d.Ticks,
                dt => new DateTimeOffset(
                        new DateTime(dt, DateTimeKind.Local).IsDaylightSavingTime() ? dt - TimeSpan.TicksPerHour : dt,
                        new TimeSpan(0)
                        )
            );

        modelBuilder.Entity<DefectReportAnswer>()
            .Property(d => d.End_date)
            .HasConversion(
                d => d.Ticks,
                dt => new DateTimeOffset(
                        new DateTime(dt, DateTimeKind.Local).IsDaylightSavingTime() ? dt - TimeSpan.TicksPerHour : dt,
                        new TimeSpan(0)
                        )
            );
    }
}

主要

private SQLiteDefectReportContext? _sqlite { get; set; }

var constring = ConfigurationManager.ConnectionStrings["DBCS"];
_sql = new SQLDefectReportContext(constringVal);

var answers = _sqlite.DefectReportAnswer
    .Where(d => d.Report_id == reportID)
    .ToArray();
c# sqlite entity-framework-core .net-8.0
1个回答
0
投票

导致意外行为的原因是模型代码中不正确的主键属性。这导致实体框架看到非不同的“键”值并创建输出。

© www.soinside.com 2019 - 2024. All rights reserved.