【问题标题】:EF Core automatically changes table name from setting to SettingsEF Core 自动将表名从设置更改为设置
【发布时间】:2020-08-30 14:43:00
【问题描述】:

我对 EF Core 生成的表名有疑问。有人可以帮忙吗?

我有一个Setting EF 配置为的实体

public class SettingConfiguration : IEntityTypeConfiguration<Setting>
{
    public void Configure(EntityTypeBuilder<Setting> builder)
    {
        builder.HasKey(c => c.Id);
        builder.ToTable<Setting>(typeof(Setting).Name.ToLower());
        builder.Property(c => c.Id).ValueGeneratedOnAdd().IsRequired().HasColumnName("id");
        builder.Property(c => c.UserId).IsRequired().HasColumnName("userId");
        builder.Property(c => c.ShowEmail).IsRequired().HasColumnName("showEmail");
    }
}

但是,当我运行 dotnet ef migrations add InitialCreate 时,我得到了

migrationBuilder.CreateTable(
            name: "Settings",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                UserId = table.Column<int>(nullable: false),
                ShowEmail = table.Column<bool>(nullable: false)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_Settings", x => x.Id);
            });

我有另一个名为 Post 的实体,其 EF 配置为

public class PostConfiguration : IEntityTypeConfiguration<Post>
{
    public void Configure(EntityTypeBuilder<Post> builder)
    {
        builder.HasKey(c => c.Id);
        builder.ToTable<Post>(typeof(Post).Name.ToLower());
        builder.Property(c => c.Id).ValueGeneratedOnAdd().IsRequired().HasColumnName("id");
        builder.Property(c => c.Title).IsUnicode().IsRequired().HasMaxLength(200).HasColumnName("title");
        builder.Property(c => c.Comment).IsUnicode().IsRequired().HasMaxLength(1000).HasColumnName("comment");
    }
}

EF Core生成的表名是post,符合预期。

migrationBuilder.CreateTable(
                name: "post",
                columns: table => new
                {
                    id = table.Column<int>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    title = table.Column<string>(maxLength: 200, nullable: false),
                    comment = table.Column<string>(maxLength: 1000, nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_post", x => x.id);
                });

【问题讨论】:

  • 顺便说一句 typeof 可以用 nameof 代替。

标签: entity-framework-core


【解决方案1】:

这是约定,您将模型定义为单数,EF 会将表名创建为复数。

如果您想摆脱这种情况,请提供[Table("YourTableName")] 属性。

【讨论】:

  • 谢谢j4rey,让我试试。但是,不确定为什么 Post 实体没有更改。请参阅我在问题中给出的示例。实际上,我还有很多其他实体,但只有 Setting 有问题。
  • 嗨@j4rey,似乎添加属性可以解决问题,但我不明白为什么这个问题只发生在Setting 而其他人
猜你喜欢
  • 2019-02-06
  • 1970-01-01
  • 1970-01-01
  • 2017-07-16
  • 2022-11-09
  • 2023-02-19
  • 2019-07-02
  • 1970-01-01
  • 2019-06-26
相关资源
最近更新 更多