InvalidOperationException when using the Set method of the DatabaseContext

0

When you use the DbContext.Set () method, the following exception is raised:

  

The entity type is not part of the model for the current   context

If I create a DbSet directly in the DatabaseContext, it works. But my current need is to create a generic repository, and from it get the DbSet for the entity passed in parameter, as the code below shows.

What is wrong with the implementation to raise this exception? I'm using CodeFirst.

Controller

public class QualquerController<TEntidade> : Controller
{
    public DatabaseContext contexto;

    public Repositorio<TEntidade> repositorio;

    public QualquerController()
    {
            repositorio = new Repositorio<TEntidade>(contexto);
    }
}

Repository

public class Repositorio<TEntidade> : where TEntidade : EntidadeBase
{
    public DbSet<TEntidade> Entidade;

    public Repositorio(DatabaseContext contexto)
    {
         Entidade = contexto.Set<TEntidade>();
    }
}
    
asked by anonymous 25.07.2014 / 21:13

2 answers

1

I was able to solve the problem through the tips that Lucas informed me. Using the Entity method of the modelbuilder passed as a parameter in the OnModelCreating method, I was able to register my entities in context. Here is the code used:

public class DatabaseContext : DbContext
{
     public DatabaseContext()
        : base("DefaultConnection")
    {
        Database.SetInitializer<DatabaseContext>(new DropCreateDatabaseAlways<DatabaseContext>());
    }

     protected override void OnModelCreating(DbModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Foo>();
         modelBuilder.Entity<Bar>();

         base.OnModelCreating(modelBuilder);
     }
}
    
26.07.2014 / 08:10
1

The point is that the contexto.Set<TEntidade>() method does not add this entity to the context. It just returns a DbSet so you can manipulate the repository.

    
25.07.2014 / 22:59