实体框架核心将空值分配给非null主键

时间:2017-02-13 22:14:36

标签: c# entity-framework .net-core entity-framework-core

更新:我已解决了这个问题。我的案例中的解决方案在我的迁移中丢失了,并且将特定于您的数据库管理器。

修复是迁移中的这一行:

Id = table.Column<long>(nullable: false)
  .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.SerialColumn)

我有一个表,我试图让EF处理id生成。 Id很长。

模型如下:

public virtual long Id { get; set; }    
public virtual DateTime Created { get; set; }

迁移看起来像:

migrationBuilder
    .CreateTable("MyEntity",
        table => new
        {
            Id = table.Column<long>(nullable: false),
            Created = table.Column<DateTime>(nullable: false)
        }

模型快照如下所示:

modelBuilder.Entity("MyEntity", b =>
                {
                    b.Property<long>("Id")
                        .ValueGeneratedOnAdd();
                    b.Property<DateTime>("Created");
                    b.HasKey("Id");
                }

当创建新实体而不设置Id时,Id的默认值为0.当将该值插入dataContext.MyEntities.Add(newEntity)并检查实体时,它现在具有极大的负值(似乎是负值) long.MaxValue)。问题是在dataContext.SaveChanges(); EF期间的某个时候似乎将此负值转换为null并抛出。

架构:

CREATE TABLE "MyEntity" (
    "Id" bigint NOT NULL,
    "Created" timestamp without time zone NOT NULL,
);

1 个答案:

答案 0 :(得分:0)

尝试:

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

或添加Key装饰器(数据注释):

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

见:

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

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