How to bring all items that have no reference with a given table [SQL]

Asked

Viewed 84 times

0

I am using Nhibernate to make a query in sql in C#, but I have a doubt.

I have the following structure:

public class Pessoa {
   public long Id {get; set;}
   public string Nome {get; set;}
}

public class Usuario {
   public long Id { //Utiliza o id da pessoa }
   public Pessoa pessoa {get; set;}
}

What I would like to do is get a listing of the people who exist but are not linked to the user, that is, all the people who can become a user.

I am currently using the following code:

[HttpGet]
public IList<Pessoa> getPessoasSemUsuarios()
{
    var usuarios = Domain.Query(); //Lista de usuários
    var pessoas = pessoaDomain.Query(); //Lista de pessoas

    var pessoasSemUsuarios = new List<Pessoa>();

    pessoas.ToList().ForEach(pessoa =>
    {
        //Adiciona todas as pessoas que não são usuários.
        if (!usuarios.Any(x => x.Pessoa.Id == pessoa.Id))
            pessoasSemUsuarios .Add(pessoa);
    });

    return pessoasSemUsuarios ;
}

Note: I thought of something related to left Outer Join, but I’m not sure, any idea ?

  • my suggestion is to use left Join, and where bring null in that Join, will be the ones that can become a user.

1 answer

0

You can make a Linq with left Join, so it will bring people who are not yet users of your system.

The code snippet would look like this:

pessoaDomain.GroupJoin(usuarioDomain,
                       pessoa => pessoa.Id,
                       usuario => usuario.IdPessoa,
                       (pessoa, usuario) => new
                       {
                            Pessoa = pessoa,
                            Usuario = usuario.DefaultIfEmpty()
                       })
           .Where(w => w.Usuario == null)
           .ToList();

Browser other questions tagged

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