I'm having trouble using PostgreSQL with Entity Framework 6.
When trying to fetch the data from my repository I get the following message:
The context can not be used while the model is being created. This exception may be thrown if the context is used inside the OnModelCreating method or if the same context instance is accessed by multiple concurrently. Note that instances of DbContext and related classes are not guaranteed to be thread safe.
Version of the software involved:
- dot.NET Version: 4.5
- PostgreSQL Version: 9.5.0
- Entity Version: 6.1.3
- Providers: EntityFramework6.Npgsql "3.0.5" and Npgsql "3.0.5"
My context class:
namespace Teste.Infra.Data.Contexto
{
public class TesteContexto : DbContext
{
public DbSet<Usuario> Usuarios { get; set; }
public DbSet<PerfilAcesso> PerfisAcesso { get; set; }
public TesteContexto () : base("name=DB_Teste")
{
var instancia = Npgsql.NpgsqlFactory.Instance;
}
protected override sealed void OnModelCreating(DbModelBuilder modelBuilder)
{
base.Database.Initialize(false);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
ConfigurarMapeamento(modelBuilder);
base.OnModelCreating(modelBuilder);
}
protected virtual void Inicializar()
{
}
protected virtual void ConfigurarMapeamento(DbModelBuilder modelo)
{
modelo.Configurations.Add(new UsuarioMapeamento());
modelo.Configurations.Add(new PerfilAcessoMapeamento());
}
}
}
Mapping Class:
public class UsuarioMapeamento : EntityTypeConfiguration<Usuario>
{
public UsuarioMapeamento()
{
ToTable("TB_USUARIOS", "public");
HasKey(d => d.UsuarioID);
Property(d => d.Nome).HasColumnName("FL_NOME").HasColumnType("varchar").IsRequired().HasMaxLength(100);
HasRequired(d => d.PerfilAcesso).WithMany().Map(e => e.MapKey("FL_PERFILACESSOID"));
}
}
Base class:
public class Usuario
{
public short UsuarioID { get; set; }
public string Nome { get; set; }
public string Email { get; set; }
public string UsuarioAcesso { get; set; }
public string SenhaAcesso { get; set; }
public DateTime DataCadastro { get; set; }
public short Situacao { get; set; }
public virtual PerfilAcesso PerfilAcesso { get; set; }
}
Note that I'm using a generic repository. Follow class:
public class RepositorioBase<T> : IDisposable, IRepositorioBase<T> where T : class
{
protected IgrejaNETContexto Contexto = new TesteContexto ();
public virtual void Adicionar(T item)
{
Contexto.Set<T>().Add(item);
Contexto.SaveChanges();
}
public virtual void Remover(T item)
{
Contexto.Set<T>().Remove(item);
Contexto.SaveChanges();
}
public virtual void Editar(T item)
{
Contexto.Entry(item).State = EntityState.Modified;
Contexto.SaveChanges();
}
public virtual T ObtemPorId(object id)
{
return Contexto.Set<T>().Find(id);
}
public IQueryable<T> Filtrar(Func<T, bool> predicate)
{
return Todos().Where(predicate).AsQueryable();
}
public virtual IQueryable<T> Todos()
{
return Contexto.Set<T>();
}
public IQueryable<T> TodosNoTracking()
{
try
{
return Contexto.Set<T>()
.AsNoTracking()
.AsQueryable();
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
Contexto.Dispose();
}
How I am trying to use the data:
UsuarioRepositorio rep = new UsuarioRepositorio();
var dados = rep.Todos();
foreach (var item in dados)
{
Console.WriteLine(item.UsuarioID + " - " + item.Nome);
}