Entity Framework Core assigning null value to non-null primary key

.net-core c# entity-framework entity-framework-core

Question

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,
);
1
0
2/14/2017 12:22:32 AM

Popular Answer

Try:

modelBuilder.Entity<MyEntity>().HasKey(e => e.Id).HasName("Id");

or adding the Key decorator (Data Annotations):

[Key]
public virtual long Id { get; set; }

See:

https://docs.microsoft.com/en-us/ef/core/modeling/relational/columns

https://msdn.microsoft.com/en-us/library/jj591583(v=vs.113).aspx

0
2/13/2017 10:20:58 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow