如何使用带有后备 C# 实体的 F# 通过 EF Core 添加具有自动生成的 ID 的行?

How to add a row with an autogenerated ID via EF Core using F# with a backing C# entity?

由于我处于早期开发阶段,我的数据库变化相对较快,因此我通过 Scaffold-DbContext 生成实体,这会产生此 C#:

public partial class User 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

// And in the DbContext:
modelBuilder.Entity<User>(entity => {
    entity.ToTable("User");
    entity.Property(e => e.Name)
        .IsRequired()
        .HasMaxLength(32)
        .IsUnicode(false);
});

这会导致我的 PK 自动递增:

这是我的失败代码:

module DbFactory =
    let options = DbContextOptionsBuilder().UseSqlServer("connectionstring").Options
    let create () = new MyDb(options)
module DbService =
    let command (q) : unit =
        use db = DbFactory.create ()
        q db |> ignore
        db.SaveChanges () |> ignore
let h = User (
        Id = Unchecked.defaultof<int>, // I've also tried -1, 0, 1, null, and removing this row entirely
        Name = "bork")
DbService.command (fun db -> db.Users.Add h)

由于我正在设置 Id,EF 抛出以下错误:

System.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'User' when IDENTITY_INSERT is set to OFF.

此未设置 Id 的 C# 代码不会发生错误:

var c = new DbFactory();
var user = new User() {
  Name = "bork",
};

var db = c.Create();
db.Users.Add(user);
db.SaveChanges();

如何让我的 F# 看起来像是没有设置 Id?由于这不是记录类型(我认为是 CLIMutable),我已经尝试 User (Name = "bork") 但也失败并出现相同的错误。

我也是 F# 的新手,如果我的 F# 可以更干净,请告诉我。

@jgoday 教会了我隔离问题的重要性。他的回答让我解脱了。