Npgsql - Entity Framework 6 Problem

Asked

Viewed 199 times

1

I am finding problems to use Postgresql together with Entity Framework 6.

When trying to fetch data from my repository I get the following message:

The context cannot 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 threads concurrently. Note that instance Members of Dbcontext and Related classes are not Guaranteed to be thread safe.

Version of the software involved:

  • Version of.NET dot: 4.5
  • Version of Postgresql: 9.5.0
  • Version of Entity: 6.1.3
  • Providers: Entityframework6.Npgsql "3.0.5" and Npgsql "3.0.5"

My kind of context:

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; }
    }

It is worth mentioning that I am using a generic repository. It follows 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’m trying to use the data:

        UsuarioRepositorio rep = new UsuarioRepositorio();
        var dados = rep.Todos();
        foreach (var item in dados)
        {
            Console.WriteLine(item.UsuarioID + " - " + item.Nome);
        }
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.