【问题标题】:Entity Framework Core 1.1 OnModelCreating method not getting calledEntity Framework Core 1.1 OnModelCreating 方法没有被调用
【发布时间】:2023-03-03 00:35:02
【问题描述】:

我已经在 .Net Standard 1.4 中创建了一个 DBContext 类,并且在 OnModelCreating 方法中有一些用于实体配置的代码,但看起来这个方法没有被调用,并且我收到一个关于列名的错误消息。

这是我的课:

public partial class TestContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(@"Data Source=blah");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestTable>().HasKey(t => t.Id).HasName("TestTableId");
        modelBuilder.Entity<TestTable>().ToTable("TestTable");
    }

    public virtual DbSet<TestTable> TestTable { get; set; }
}

public class TestTable
{
    public Guid Id { get; set; }
    public string Name { get; set; }
}

当我尝试查询这个 TestTable 时,我收到一条错误消息 invalid column name "Id"

我在表中没有Id,我有TestTableId,我希望我得到的OnModelCreating 代码能够处理该映射。

有什么想法吗?

【问题讨论】:

    标签: asp.net-core .net-core entity-framework-core asp.net-core-webapi .net-standard


    【解决方案1】:

    您遇到的问题是您在这里命名键而不是列:

    modelBuilder.Entity<TestTable>()
        .HasKey(t => t.Id)
            .HasName("TestTableId");
    

    这将创建一个主键,然后将该键命名为 TestTableId。你应该做的是:

    modelBuilder.Entity<TestTable>()
        .Property(t => t.Id)
            .HasColumnName("TestTableId");
    

    【讨论】:

      猜你喜欢
      • 2021-06-07
      • 2016-11-08
      • 1970-01-01
      • 2017-10-27
      • 2022-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多