获取所有别名的列表并与名称联合

Get a list of all aliases and union with name

假设我有以下实体。

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

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

给定产品 ID,如何在单个查询中创建包含产品 Name 本身的该产品的所有别名列表?

我不知道我是否可以做类似下面的事情。此语法无效,因为 Union() 不采用 lambda 表达式。

DbContext.Products
    .Where(p => p.Id == productId)
    .Select(p => p.Name)
    .Union(p => p.ProductAliases.Select(a => a.Alias))
    .ToList();

加入IdProductId上的两个表,select所有需要的属性 (Id, Name, Alias) 并过滤 Id.

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

另一种形式:

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

结果(使用 LINQ2Object 进行测试,但它应该也适用于 LINQ2SQL):

尝试以下操作:

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

您可以像这样执行 SQL 服务器逆轴旋转的等效操作

DbContext.Products
    .Where(p => p.Id == productId)
    .SelectMany(p => p.ProductAliases.Select(a => a.Alias).Append(p.Name))
    .ToList();