📜  ef core totable (1)

📅  最后修改于: 2023-12-03 15:14:50.915000             🧑  作者: Mango

EF Core ToTable

EF Core ToTable is a method used in Entity Framework Core to specify the database table name for an entity. By default, EF Core will use the entity class name as the table name in the database. However, in some cases, we may want to specify a different table name for the entity. This is where the ToTable method comes in handy.

Syntax

The syntax for using ToTable method is:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<EntityClassName>().ToTable("TableName");
}

Where EntityClassName is the name of the entity class and TableName is the database table name we want to specify for the entity. This method needs to be called inside the OnModelCreating method of the DbContext class.

Example
public class MyDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().ToTable("tblCustomers");
    }
}

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
}

In the above example, we have specified the table name "tblCustomers" for the Customer entity using the ToTable method.

Conclusion

EF Core ToTable method is used to specify the database table name for an entity. By default, EF Core uses the entity class name as the table name. To use a custom name for the table, we can use the ToTable method inside the OnModelCreating method of the DbContext class.