【问题标题】:EF6: migration generates nullable string despite IsRequiredEF6:尽管 IsRequired,迁移仍会生成可为空的字符串
【发布时间】:2019-08-21 22:13:29
【问题描述】:

我正在尝试为具有 string 字段的新实体类生成迁移,该字段名为 "Name"。该字符串字段不应为空。

我知道“可为空”和“非空”是两个不同的问题(请参阅 EF 6 IsRequired() allowing empty strings )。但现在我只想坚持非空。

我没有做到这一点。生成的迁移总是以 "nullable:true" 结束,如图所示:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "Tags",
            columns: table => new
            {
                // ...
                Name = table.Column<string>(nullable: true),
                // ...
            },
            // ...
    }

我知道我可以通过注释 (EF6 Add-Migration for not nullable string?) 来实现这一点,但我们的架构师禁止这样做。我需要坚持IEntityTypeConfiguration中的Configure功能。

我正在使用 IsRequired()

public class TagEntityTypeConfiguration : IEntityTypeConfiguration<Tag>
{
    public void Configure(EntityTypeBuilder<Tag> builder)
    {
        builder.ToTable("Tag");

        builder.HasKey(x => x.Id);

        builder.Property(t => t.Name)
            .IsRequired()
            .HasMaxLength(100);

    }
}

为什么我得到 nullable:true 尽管 .IsRequired ?

【问题讨论】:

    标签: entity-framework non-nullable


    【解决方案1】:

    我只是忘记使用 EntityTypeConfiguration :

            modelBuilder.ApplyConfiguration(new TagEntityTypeConfiguration());
    

    没有这条线,约束将被忽略。

    【讨论】:

      猜你喜欢
      • 2021-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-18
      • 2019-11-17
      • 1970-01-01
      相关资源
      最近更新 更多