Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
Get a list of all aliases and union with name

Let's say I have the following entities.

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class ProductAlias
{
    public int ProductId { get; set; }
    public string Alias { get; set; }
}

Given a product ID, how could I create a list of all aliases for that product that includes the product Name itself in a single query?

I don't know if I can do something like the following. This syntax doesn't work because Union() doesn't take a lambda expression.

DbContext.Products
    .Where(p => p.Id == productId)
    .Select(p => p.Name)
    .Union(p => p.ProductAliases.Select(a => a.Alias))
    .ToList();
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

Join the two tables on Id and ProductId, select all the needed attribuites (Id, Name, Alias) and filter on Id.

products
.Join(aliases, p => p.Id, a => a.ProductId, (p,a) => new { p.Name, p.Id, a.Alias})
.Where(p => p.Id == productId);

In another form:

(from p in products
    join a in aliases on p.Id equals a.ProductId
    select new  
    {
        p.Name,
        p.Id,
        a.Alias
    })
.Where(p => p.Id == productId);

The result (with LINQ2Object for the test, but it should work also with LINQ2SQL):

enter image description here

over 4 years ago · Santiago Trujillo Relatório

0

Try the following:

var products = DbContext.Products
    .Where(p => p.Id == productId);

products
    .Select(p => p.Name)
    .Union(products.SelectMany(p => p.ProductAliases.Select(a => a.Alias)))
    .ToList();
over 4 years ago · Santiago Trujillo Relatório

0

You can do the equivalent of a SQL Server unpivot like this

DbContext.Products
    .Where(p => p.Id == productId)
    .SelectMany(p => p.ProductAliases.Select(a => a.Alias).Append(p.Name))
    .ToList();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda