Object Type Declaration Doubt - Entity Framework

Asked

Viewed 75 times

2

I need help in defining the correct class statement

Follows my code:

public void BuscaOcorremcias()
{
    //Op 01 - Declarando um IList da Model
    IList<Ocorrencia> ocorrencias = null;
    //Op 02 - Declarando um DbSet
    System.Data.Entity.DbSet<MoradaWeb.Models.Ocorrencia> ocorrencias = null;

    ocorrencias = db.Ocorrencia.Include("Pessoa").Where(c => c.status == true);

    if (MinhaRegradeNegocio)
        ocorrencias = ocorrencias.Where(c => c.Pessoa == PessoaLogada);
}

//My Context

public class MeuContext : DbContext
{
    public MoradaWebContext() : base("name=MinhaConnectionString")
    {   ...   }

    public System.Data.Entity.DbSet<Models.Ocorrencia> Ocorrencia { get; set; }
}

The error that occurs with the above two options (in the code comment) is this:

Cannot implicititly Convert type...

I’m not sure what kind to declare so I can maintain the condition of applying an extra Where if I have to. In this case I want to make the second Where inside the collection itself that has already been searched in the bank.

  • State as var ocorrencias = db.Ocorrencia.Include("Pessoa").Where(c => c.status == true); and see the type defined by placing the mouse cursor over the variable occurrences.

1 answer

5


IS IQueryable what you need.

If you are selecting only the DbSet (db.Ocorrencia, in the example) it is also necessary to call the method AsQueryable because his type is just DbSet. From the first Include, Where or related the type returned becomes a IQueryable.

You can see more details, in this question of mine.

IQueryable<Ocorrencia> ocorrencias = db.Ocorrencia.Include("Pessoa")
                                       .Where(c => c.status == true);

if (MinhaRegradeNegocio)
    ocorrencias = ocorrencias.Where(c => c.Pessoa == PessoaLogada);

It is also possible to use var and let the type be set automatically.

  • jbueno, your link was very helpful. Thank you. I managed to resolve by going straight to Ienumerable<T>

  • 1

    @Brunoheringer Going straight to Ienumerable you bring all the records to the memory before the second filter

  • Good observation... too much vlw...

Browser other questions tagged

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