Junior — Middle
How does Entity Framework determine the corresponding model class when working with a database?
sobes.tech AI
Answer from AI
Entity Framework (EF) determines the corresponding model class for a database table based on the model configuration, which is usually specified in code using context classes (DbContext) and DbSet<T> properties.
Main mapping methods:
- By class name and table name: EF by default maps the model class to a table with the same name as the class (considering naming conventions).
- Through attributes (Data Annotations), e.g.,
[Table("TableName")], which explicitly specify the table name. - Through Fluent API in the
OnModelCreatingmethod of the context class, where you can configure mappings between classes and tables, as well as between properties and columns.
Example:
public class MyContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("UsersTable");
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
Here, EF knows that the User class corresponds to the UsersTable table.
Thus, EF uses configuration and conventions to determine which model class is associated with which table in the database.