Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Month Name from datetime column in Linq to SQL?

I have a DateTime column in my table.

In Linq to SQL query, I only need Month part of that field

How to write the Linq query for that?

like image 538
Mohammed Shafeeq Avatar asked Mar 04 '12 14:03

Mohammed Shafeeq


Video Answer


2 Answers

Well, there are three options I can immediately think of:

  • Pull the whole DateTime back, and then extract the month and format it client-side
  • Use DateTime.Month to pull just the month back from the database, then format it client-side
  • Try to get the formatting (conversion to text) to work on the database

Personally I would not try the third option - it feels to me like it's very unlikely to work, at least without a lot of effort.

I suspect I'd actually just pull the DateTime back, and do everything client-side. It's very easy to do that, and it's bound to work. I expect DateTime.Month will probably work, but you're not going to be saving very much network bandwidth, and you'll be getting the server to do work which is probably just as easy for the client to do.

Note that if you still want the results as a query, you can use AsEnumerable to force the remainder of the query to be done client-side. For example:

var query = db.Customers
              .Where(c => c.OrderCount > 500) // Or whatever query you want
              .Select(c => new { c.Name, c.FirstOrder })
              .AsEnumerable() // Do the rest of the query on the client
              .Select(c => new { c.Name, c.Month = c.FirstOrder.ToString("MMM") });

EDIT: As noted in comments, it makes sense to use DateTime.Month on the server side if it will actually affect the results, e.g.

var query = db.Customers.Where(c => c.FirstOrder.Month == 1)
                        ...

... but in those cases I'd expect it to be the numeric value which is important, not the name of the month.

like image 159
Jon Skeet Avatar answered Oct 27 '22 07:10

Jon Skeet


Something like:

string monthName = dataContext.GetTable<TableName>()
                              .FirstOrDefault(t => t.DateTimeColumn)
                              .ToString("MMM");               
like image 34
Mahmoud Gamal Avatar answered Oct 27 '22 09:10

Mahmoud Gamal