Search code examples
c#linqservice

How could I rewrite this LINQ query in a fluent style from sql like style?


I need to write this linq query ("where result =") in a fluent LINQ style.

public async Task<List<Product>> ListProductsInOrderByOrderId(int orderId)
{
    var productsList = await _context.OrderProducts.Where(or => or.OrderId == orderId).ToListAsync();

    var result =  from prod in _context.Products
        join meta in _context.OrderProducts on prod.Id equals meta.ProductId 
        select new Product
                        {
                            Id = prod.Id,
                            Name = prod.Name,
                            Genre = prod.Genre,
                            RatingByAge = prod.RatingByAge,
                            DateCreated = prod.DateCreated,
                            Price = prod.Price,
                            Count = prod.Count,
                            TotalRating = prod.TotalRating

                        };

    var collectionOfProducts = await result.ToListAsync();

    return collectionOfProducts;
}

Could you help me?


Solution

  • This should work:

    var result = _context.Products.
      Join(_context.OrderProducts, prod => prod.prodId, meta => meta.ProductId, (prod,meta) => new { prod, meta }).
      Select(x => new Product
      {
         Id = x.prod.Id,
         Name = x.prod.Name,
         Genre = x.prod.Genre,
         RatingByAge = x.prod.RatingByAge,
         DateCreated = x.prod.DateCreated,
         Price = x.prod.Price,
         Count = x.prod.Count,
         TotalRating = x.prod.TotalRating
      });