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();
>Solution :
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();