Is this Linq query a currect way to retrieve data or there are more effective ways?

Viewed 75

This code works but I've heard from somewhere that when we use Select it pushes to execute Join operation. So will it considered a slow operation, or by the way is there a way/ program to check linq queries correctness, performance ...

public IQueryable<Entity> GetById(int id){return_context.Set<Entity().Where(p => p.Id == id);}

var actor = _repository.GetById(id)
    .Select(a => new 
    { 
        a.Id,
        a.FirstName, 
        a.LastName, 
        a.Bio, 
        a.Birthday, 
        a.Height, 
        a.Image,    
        Country = new 
        {
            a.Country.Id, 
            a.Country.Name 
        }, 
        Movies = a.ActorMovies
            .Select(am => new 
            {
                am.Movie.Title,
                am.Movie.Year,
                am.Movie.Image 
            })
    }).FirstOrDefault();
1 Answers

Yes, that query will use a join -- not because it's written in LINQ, but because you specifically ask it to join to another table (in setting the Movies property). There's no way I can see it get that result (efficiently) without using the join.

However, there is a problem with that code. I'm assuming that this is taken from your business layer. Actually, almost all of that should be in the repository. Your only line in the business layer should be:

var actor = _repository.GetActorWithMoviesById(id);
Related