6

How do you explicitally tell EF that a table lies in a specific schema?

For example, the AdventureWorks database defines the Production.Product table. When using the OnModelCreating method, I use the following code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    EntityTypeConfiguration<Product> config = modelBuilder.Entity<Product>();

    config.HasKey(p => p.ProductID);
    config.Property(p => p.Price).HasColumnName("ListPrice");
    config.ToTable("Product");
}

However, when it is run, it says it Invalid object name: dbo.Product.

I have tried:

config.ToTable("Production.Product");
//and
config.HasEntityName("Production");

but both fail as well.

Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61

2 Answers2

14

ToTable has overloaded version which accepts two parameters: table name and schema name so correct version is:

config.ToTable("Product", "Production");
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
0

The table schema can also be specified using data annotations using the optional parameter 'Schema' on the 'Table' attribute.

using System.ComponentModel.DataAnnotations.Schema;

[Table("Product", Schema="Production")]
public class Product
{
    public int ProductID { get; set; }
    public decimal Price { get; set; }
}
David Sopko
  • 5,263
  • 2
  • 38
  • 42