Question

I have SQL Query like this :

  select top 1 Newsletter_HTML_Tag  from Newsletter_TBL
     where (Newsletter_Category_ID=1)
     order by Creation_Date desc

and I also have a method which give me the list of all records from Newsletter_TBL named:

NewsletterGellAll()

and I have tried it before, but it doesn't work:

NewsletterGellAll()
   .FirstOrDefault(c => c.NEWSLETTER_CATEGORY_ID == 1)
   .orderby(a => a.Creation_Date)

How can I fix it?

No correct solution

OTHER TIPS

It should be OrderByDescending instead of OrderBy if you want to replicate the results for the SQL Query.

Additionally, if you look at your query:

NewsletterGetAll()
.FirstOrDefault(c => c.NEWSLETTER_CATEGORY_ID == 1)
.OrderBy(a => a.Creation_Date)

In SQL this would be ok, since it evaluates the ORDER BY before the TOP expression. However, in Linq it will take the first record that matches the category, and then order that single record. So this won't even build, you cannot sort a single item.

Therefore it should be

NewsletterGetAll()
.Where(c => c.NEWSLETTER_CATEGORY_ID == 1)
.OrderByDescending(c => c.Creation_Date)
.FirstOrDefault();

use LINQPad and make professional LINQ and SQL queries. here is linqpad

It is always advisable to use First or Default when you are not sure that condition will not be satisfied, as this will also handle null case. Means, if there are no records (with specific condition).

Depends of order to Date as well, here consider that date is ascending, (older date first)

NewsletterGellAll().Where(c=>c.NEWSLETTER_CATEGORY_ID==1)
                    .OrderBy(a=>a.Creation_Date)
                    .FirstOrDefault();

First query all items with cat==1, then order it to get the first

NewsletterGellAll().Where(c=>c.NEWSLETTER_CATEGORY_ID==1)
                   .OrderBy(a=>a.Creation_Date)
                   .First();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top