Method that works without calling you directly

0

I'm messing with the Entity Framework and I was doing mapping for a Many to Many class.

What happens is that I used a method that I can use within DbContext to rename a table, and it works without problems.

But I was wondering how this method works, since I do not call it anywhere in my program? In this case it would be the OnModelCreating() method.

class EfContext : DbContext
{
    public DbSet<Editora> EditorasDbSet { get; set; }
    public DbSet<Cliente> ClientesDbSet { get; set; }
    public DbSet<Estado> EstadosDbSet { get; set; }
    public DbSet<Governador> GovernadorsDbSet { get; set; }
    public DbSet<Departamento> DepartamentosDbSet { get; set; }
    public DbSet<Funcionario> FuncionariosDbSet { get; set; }
    public DbSet<Pedido> PedidosDbSet { get; set; }
    public DbSet<Consumidor> ConsumidoresDbSet { get; set; }
    public DbSet<Autor> AutorsDbSet { get; set; }
    public DbSet<Livro> LivrosDbSet { get; set; }

    public EfContext()
    {
        CustomDBInitializer initializer = new CustomDBInitializer();
        Database.SetInitializer<EfContext>(initializer);
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Autor>().HasMany(autor => autor.Livros).WithMany(livro => livro.Autores).Map( x => 
        {
            x.ToTable("livros_e_autores");
            x.MapLeftKey("autor_id");
            x.MapRightKey("livro_id");
        });
    }

}
    
asked by anonymous 21.08.2018 / 21:05

1 answer

2

First you need to understand what is a framework .

You are inheriting from DbContext that the Entity Framework knows what it is and knows that there is a OnModelCreating() method. Somewhere within every infrastructure of EF this method is called when appropriate. He knows when he needs it.

What it lets you do is write the implementation of this method in its inherited class class, so it establishes the virtual and you do it with override .

Then when you pass a EfConetxt object to a place that expects a DbContext , after all they are compatible, and that is polymorphism , it will call its method and not the DbContext method. He knows what to call but does not know what will run, you define it. Smart, is not it?

A different example of this can be seen in What is the difference between using virtual property and not in EF? .

    
21.08.2018 / 21:15