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

Asked

Viewed 131 times

1

I’m trying to reproduce this example of Entityframework with default repository, as follows the link: https://msdn.microsoft.com/pt-br/library/dn630213.aspx

But it is giving the error described in the title of the topic.

I’ll post the codes.

The first is the Bancocontexto.Cs class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Repositorio.Entidades;

namespace Repositorio.DAL.Contexto
{
    public class BancoContexto : DbContext
{
    public BancoContexto() : base("ConnDB") { }

}
}

The second is the Irepositorio.Cs interface:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repositorio.DAL.Repositorios.Base
{
interface IRepositorio<TEntity> where TEntity : class
{
    IQueryable<TEntity> GetAll();
    IQueryable<TEntity> Get(Func<TEntity, bool> predicate);
    TEntity Find(params object[] key);
    void Atualizar(TEntity obj);
    void SalvarTodos();
    void Adicionar(TEntity obj);
    void Excluir(Func<TEntity, bool> predicate);
}
}

The third is the Repositorio.Cs class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Repositorio.DAL.Contexto;

namespace Repositorio.DAL.Repositorios.Base
{
public abstract class Repositorio<TEntity> : IDisposable,
   IRepositorio<TEntity> where TEntity : class
{
    BancoContexto ctx = new BancoContexto();
    public IQueryable<TEntity> GetAll()
    {
        return ctx.Set<TEntity>();
    }

    public IQueryable<TEntity> Get(Func<TEntity, bool> predicate)
    {
        return GetAll().Where(predicate).AsQueryable();
    }

    public TEntity Find(params object[] key)
    {
        return ctx.Set<TEntity>().Find(key);
    }

    public void Atualizar(TEntity obj)
    {
        ctx.Entry(obj).State = EntityState.Modified;
    }

    public void SalvarTodos()
    {
        ctx.SaveChanges();
    }

    public void Adicionar(TEntity obj)
    {
        ctx.Set<TEntity>().Add(obj);
    }

    public void Excluir(Func<TEntity, bool> predicate)
    {
        ctx.Set<TEntity>()
            .Where(predicate).ToList()
            .ForEach(del => ctx.Set<TEntity>().Remove(del));
    }

    public void Dispose()
    {
        ctx.Dispose();
    }
}
}

The fourth class is Clienterepositorio.Cs:

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Text;
using System.Threading.Tasks;
using Repositorio.DAL.Repositorios.Base;
using Repositorio.Entidades;

namespace Repositorio.DAL.Repositorios
{
public class ClienteRepositorio : Repositorio<Cliente>
{
}
}

The fifth class is Customer.Cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Repositorio.Entidades
{
public class Cliente
{
    public int ClienteID { get; set; }
    public string Nome { get; set; }
    public string CNPJ { get; set; }
    public string Endereco { get; set; }
    public string Telefone { get; set; }
    public bool Ativo { get; set; }
}
}

The last is the console class, Program.Cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Repositorio.DAL.Repositorios;
using Repositorio.Entidades;

namespace Repositorio.Console
{
class Program
{
    static void Main(string[] args)
    {
        Adicionar();
    }

    private static void Adicionar()
    {
        using (var repClientes = new ClienteRepositorio())
        {
            new List<Cliente>
            {
                new Cliente { Nome="Microsoft", Ativo=true, CNPJ="9394.4343/0001-55", 
                                Endereco="1, Microsoft One", Telefone="11574739494"},
                new Cliente { Nome="Google", Ativo=true, CNPJ="1234.9494/0001-33", 
                                Endereco="12, Santa Clara, CA", Telefone="1185858483"},
                new Cliente { Nome="Oracle", Ativo=true, CNPJ="9876.4433/0002-44", 
                                Endereco="54, Santa Monica", Telefone="4884848592"}
            }.ForEach(repClientes.Adicionar);

            repClientes.SalvarTodos();

            System.Console.WriteLine("Clientes adicionadas com sucesso.");

            System.Console.WriteLine("=======  clientes cadastrados ===========");
            foreach (var c in repClientes.GetAll())
            {
                System.Console.WriteLine("{0} - {1}", c.ClienteID, c.Nome);
            }

            System.Console.ReadKey();
        }
    }
}
}

I will leave the App.config file of the layer where the console class is located:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="ConnDB" connectionString="Data Source=joao\sqlexpress;Initial Catalog=db_repositorio;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
 <providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>

 </configuration>

1 answer

3


Besides complicating much which is extremely simple (implement a second repository instead of working directly with EF), this tutorial is wrong.

In the context, the DbSet with the model Cliente.

namespace Repositorio.DAL.Contexto
{
    public class BancoContexto : DbContext 
    {
        public BancoContexto() : base("ConnDB") { }

        public DbSet<Cliente> Clientes { get; set; }
    }
}

Explaining:

This error happens because (as the error itself says) the entity type is not part of the model for the context you have at the moment. By doing this

ctx.Set<TEntity>().Add(obj); //Ao executar o código, TEntity vai ser Cliente

the code is saying, "Hey context, go on your Dbsets and look for Dbset Cliente, then add this object to it!". Since there is no declared Dbset, the context complains that "the type of entity is not part of the model for the current context". =)


Here is a very interesting question about using Repository Pattern with Entity Framework. I think it would be extremely important for you to read it and try to draw your own conclusions about the use of it.

  • Excellent! It worked... Thank you very much. I noticed that you named the Dbset Client as Customers, right? Is this related to the creation of the table he generated in the database I’m using? If I create more entity classes and declare them later in Dbset just like you did with Client, will they also be generated? I read the question and also the answer you gave me, it is very explanatory and enlightening by the way, thank you again.

  • You said that this tutorial that I based is wrong for implementing a second repository instead of working directly with EF. Where can I find a correct tutorial, because I have searched for several, but I did not succeed in the search. And sorry for the long comment, I’m really impressed by that.

  • This "maps" your model Cliente within the context. All Dbsets will turn tables in the database. Yes, if you create more classes and put them there, they will be generated as well.

  • Behold this series of tutorials on the official ASP.NET website, they are great and simple. By the way, I didn’t say which approach is wrong, after all it works. I just said that it complicates too much what is simple =)

  • I’ll look for it for sure! My last question is whether I can add Dbsets as needed or if I recommend adding them only when they are finished and no longer need to be changed.

  • Change them at will. Development environment serves for this =)

  • My dear, thank you very much, for clearing all these doubts.

  • It’s a pleasure to help =)

Show 3 more comments

Browser other questions tagged

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