locked
Convert sql to linq/entiti framework RRS feed

  • Question

  • Hi, Im trying to write that query in an mvc aplicattion and I just couldnt. 

    select distinct Usuario.idUsuario, Usuario.Nombre, Usuario.DNI from Usuario right join Relaciones on (Usuario.idUsuario = Relaciones.idUsuario) inner join Cursos on (Relaciones.idCurso = Cursos.idCurso)

    Saturday, November 7, 2015 7:04 PM

Answers

  • Since you are only selecting data from the Usuario table, there is no reason to JOIN the other tables like you are doing. If you only want Usuarios with a Relacione this should work:

    var res = 
    (from r in context.Relaciones
    join u in context.Usuario on u.idUsuario equals r.idUsuario
    select u).Distinct();

    You could also JOIN on Cursos:

    var res = 
    (from r in context.Relaciones
    join u in context.Usuario on u.idUsuario equals r.idUsuario
    join c in context.Cursos on r.idCurso equals c.idCurso
    select u).Distinct();

    Please refer to the following two links for more examples of how to JOIN in Linq-To-Entities:
    https://itworksonmymachine.wordpress.com/2009/09/27/sql-to-linq-cheat-sheet/
    https://smehrozalam.wordpress.com/2009/06/10/c-left-outer-joins-with-linq/

    Hope that helps.

    Please remember to close your threads by marking helpful posts as answer and then start a new thread if you have a new question.  Please don't ask several questions in the same thread.

    Wednesday, November 11, 2015 1:04 PM

All replies