Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading