Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a Table; Material_Price with the following structure:

Material_ID, EffectiveDate, Price

In TSQL I do this:

SQL
DECLARE @Id INT = 1

SELECT Price
  FROM Material_Price
  WHERE Material_ID = @Id
    AND EffectiveDate = (SELECT (MAX)EffectiveDate
                           FROM Material_Price
                           WHERE Material_ID = @Id
                             AND EffectiveDate <= GetDate())


What is the equivalent in a linq query?
Posted

Typed over my head (might have some error), should be something like:
C#
var effDate = (from mp in dataContext.Material_Price
               where mp.Material_ID = @id and mp.EffectiveDate <= DateTime.Now
               select mp.EffectiveDate).Max();
			   
var query = from mp  in dataContext.Material_Price
            where mp.Material_ID = @id and effDate.Contains(mp.EffectiveDate)
	    select mp.Price;



A helpful tool: LinqPad[^]

Just in case needed, following articles would help:
Learn SQL to LINQ (Visual Representation)[^]
Converting SQL to LINQ, Part 1: The Basics (Bill Horst)[^]
 
Share this answer
 
Comments
Monjurul Habib 17-Feb-13 6:22am    
5+
With a few minor changes, here is the completed snippet:

C#
var effDate = (from mp in db.Material_Price
            where mp.Material_ID == id && mp.EffectiveDate <= DateTime.Now
                select mp.EffectiveDate).Max();

var query = from mp  in db.Material_Price
      where mp.Material_ID == id
                && effDate.CompareTo(mp.EffectiveDate) == 0
      select mp.Price;


Thanks Sandeep, magic!

I was hoping however that it could be done with a single statement.
 
Share this answer
 
v2
Comments
Monjurul Habib 17-Feb-13 6:22am    
5+

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900