Update: I have fixed the problem. The solution in my case was missing from my migration and will be specific to your database manager.
The fix is this line in the migration:
Id = table.Column<long>(nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)
I have a table that I am trying to let EF handle the id generation. The Id is a long.
The model looks like:
public virtual long Id { get; set; }
public virtual DateTime Created { get; set; }
The migration looks like:
migrationBuilder
.CreateTable("MyEntity",
table => new
{
Id = table.Column<long>(nullable: false),
Created = table.Column<DateTime>(nullable: false)
}
The model snapshot looks like:
modelBuilder.Entity("MyEntity", b =>
{
b.Property<long>("Id")
.ValueGeneratedOnAdd();
b.Property<DateTime>("Created");
b.HasKey("Id");
}
When creating a new entity and not setting the Id, the Id has the default value of 0. When inserting that value into dataContext.MyEntities.Add(newEntity)
and inspecting the entity it now has an extremely large negative value (seems to be negative long.MaxValue). The problem is that sometime during the dataContext.SaveChanges();
EF seems to convert this negative value into null and throws.
Schema:
CREATE TABLE "MyEntity" (
"Id" bigint NOT NULL,
"Created" timestamp without time zone NOT NULL,
);