Click here to Skip to main content
11,705,212 members (47,692 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: LINQ SQL
I have a Table; Material_Price with the following structure:

Material_ID, EffectiveDate, Price

In TSQL I do this:

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 16-Feb-13 15:59pm
Andy_L_J19.9K
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Typed over my head (might have some error), should be something like:
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)[^]
  Permalink  
Comments
Monjurul Habib at 17-Feb-13 6:22am
   
5+
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

With a few minor changes, here is the completed snippet:

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.
  Permalink  
v2
Comments
Monjurul Habib at 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)

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 550
1 OriginalGriff 244
2 ppolymorphe 126
3 CPallini 82
4 F-ES Sitecore 70
0 OriginalGriff 8,988
1 Sergey Alexandrovich Kryukov 8,272
2 CPallini 5,189
3 Maciej Los 4,726
4 Mika Wendelius 3,606


Advertise | Privacy | Mobile
Web04 | 2.8.150819.1 | Last Updated 17 Feb 2013
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100