Aram
Aram

Reputation: 5705

Entity Framework Core 1.1 OnModelCreating method not getting called

I have created a DBContext class in a .Net Standard 1.4 and have some code for entity configuration, in the OnModelCreating method, but it looks like this method is not getting called and I am getting an error complaining about a column name.

Here is my class:

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; }
}

When I try to query this TestTable, I get an error saying invalid column name "Id"

And I don't have Id in the table, and I have TestTableId, and I was hoping the OnModelCreating code I got will take care of that mapping.

Any Ideas?

Upvotes: 2

Views: 878

Answers (1)

DavidG
DavidG

Reputation: 118987

The problem you have is that you are naming the key and not the column here:

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

This creates a primary key and then names that key TestTableId. What you should be doing is this:

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

Upvotes: 2

Related Questions