1

I have some difficulties when it comes to multi-table query in Linq to Sql. I have 3 tables:

  • Product
  • Row (with Fk-ProductId)
  • Price (with Fk-RowId)

I'd like to retrieve the min(Price) for a product. I was able to get the right Sql query, but now I need to 'translate' this query into Linq To Sql. Can you please help me ?

Here the Sql query:

SELECT Min(cp.Price) 
FROM Products p, Rows r, ConstantPrices cp 
WHERE p.ProductId = r.ProductId AND 
      r.RowId = cp.RowId AND 
      p.ProductId = XXX;
0

2 Answers 2

1

Here's a solution:

decimal? min = (from p in db.Products
               join r in db.Rows on p.ProductId equals r.ProductId
               join cp in db.ConstantPrices on r.RowId equals cp.RowId
               where p.ProductId == 1
               select cp.Price).Min();
Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget to make the field nullable, as I mentioned in my answer not doing so would throw an exception if there are no items.
0
var productQuery = from p in myContext
               where p.id == someId
               select (double?) p.Row.Price;
var minPrice = productQuery.Min();

Its important the nullable in there, otherwise it would fail if there are no products or rows or prices in the system.

Its not about translating queries, its about taking advantage of what linq2sql gives you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.