The Fluent API ToTable Method

The ToTable method is applied to an entity to specify the name of the database table that the entity should map to. The following example specifies that the Book entity should map to a database table named tbl_Book:

public class SampleContext : DbContext
{
    public DbSet<Book> Books { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Book>()
            .ToTable("tbl_Book`");
    }
}

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
}

An overload of the method maps the entity to a non-default schema:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Book>().ToTable("tbl_Book", "library");
}

Data Annotations

The Data Annotation equivalent to the ToTable method is the Table attribute


Created:
Last updated: 14/03/2017 16:33:45
Proficiency Level: Beginner