Get null fields from the database with LINQ

Asked

Viewed 71 times

4

I have a table of Gestor in the database where you store information of a user with Manager profile. In this table, I have two FK's: uniaoId and schoolboy. Well, that manager MUST belong to a union and may or may not belong to a school. That’s my problem. When I do Join with Ingl, it doesn’t bring managers who don’t belong to a school. I tried the next one, but it didn’t work:

var listaRelatorioEmail = (
    from ge in db.Gestor
        join uni in db.Uniao on ge.UniaoId equals uni.UniaoId into uni_join
    from uni in uni_join.DefaultIfEmpty()                                               
        join es in db.Escola on ge.EscolaId equals es.EscolaId into es_join
    from es in es_join.DefaultIfEmpty()                                                 
        select new
        {
            UniaoNome = uni.Nome,
            UniaoId = uni.UniaoId,
            EscolaNome = es.Nome,
            EscolaId = es.EscolaId,
        }).ToList();

2 answers

3


I chose to do the same thing with Extension Methods. Worked perfectly with the following code:

var listaRelatorioEmail = db.Gestor.Select(a => new
                             {
                                 UniaoNome = a.Nome,
                                 UniaoId = a.UniaoEntidadeId,
                                 EscolaNome = a.Nome,
                                 EscolaId = a.EscolaId == null ? 0 : a.EscolaId.Value
                             }).ToList();

-1

I’m not sure I understand, but, try to change the school Join to left Join so it brings all managers and if n has school it puts null if I am not mistaken

var listaRelatorioEmail = (
from ge in db.Gestor
    join uni in db.Uniao on ge.UniaoId equals uni.UniaoId into uni_join
from uni in uni_join.DefaultIfEmpty()                                               
    **left join** es in db.Escola on ge.EscolaId equals es.EscolaId into es_join
from es in es_join.DefaultIfEmpty()                                                 
    select new
    {
        UniaoNome = uni.Nome,
        UniaoId = uni.UniaoId,
        EscolaNome = es.Nome,
        EscolaId = es.EscolaId,
    }).ToList();
  • There is no left Join on LINQ.

Browser other questions tagged

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