You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

EF Core数据库优先模式下无主键表的数据插入问题求助

解决方法

标记[Keyless]的实体不被EF Core变更跟踪器支持,因此无法使用Add方法插入数据,可通过以下两种方式解决:

方法一:使用原生SQL语句插入

绕过实体跟踪机制,直接执行原生SQL完成插入操作,修改AddAttendance方法如下:

public bool AddAttendance(Attendance attendance)
{
    try
    {
        _dbContext.Database.ExecuteSqlInterpolated($@"
            INSERT INTO Attendances (Barcode, Code, Country, EntryTime, CreatedBy, GateId)
            VALUES ({attendance.Barcode}, {attendance.Code}, {attendance.Country}, {attendance.EntryTime}, {attendance.CreatedBy}, {attendance.GateId})
        ");
        return true;
    }
    catch (Exception ex)
    {
        // 可添加日志记录逻辑
        return false;
    }
}

方法二:配置EF Core模拟主键(无需修改数据库)

如果想继续使用实体类操作,可以在DbContext中指定组合字段作为EF Core识别的主键(数据库无需改动):

  1. 移除实体类上的[Keyless]特性:
public class Attendance
{
    public string Barcode { get; set; }
    public string? Code { get; set; }
    public string? Country { get; set; }
    public DateTime EntryTime { get; set; }
    public string CreatedBy { get; set; }
    public int GateId { get; set; }
}
  1. 在DbContext的OnModelCreating方法中配置组合键:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // 选择能唯一标识单条记录的字段组合,比如Barcode+EntryTime+GateId
    modelBuilder.Entity<Attendance>()
        .HasKey(a => new { a.Barcode, a.EntryTime, a.GateId });
}

配置完成后,即可正常使用Add和SaveChanges方法插入数据,注意确保所选组合字段在数据库中具备唯一性,避免跟踪异常。

内容的提问来源于stack exchange,提问作者Shakil Ahmed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 08:28:15