Entity Framework Core 1.1 OnModelCreating method not getting called

.net-core .net-standard asp.net-core asp.net-core-webapi entity-framework-core

Question

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?

1
2
6/15/2017 11:46:44 PM

Accepted Answer

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");
2
6/16/2017 9:28:35 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow