Wednesday, July 27, 2011

A Tip For Writing Entity Framework Queries Using DateTime Values

Today I found a nice utility method for working with DateTime values in Entity Framework LINQ queries. I wanted a list of Events which fell between a date range, but my query needed to ignore the time portion of the DateTime values. My first attempt was this:

var events = this.coreDomainContext.Events.Where(
    e => e.EventDate.Value.Date >= DateTime.Today
      && e.EventDate.Value.Date <= endPeriod.Date)
    .OrderByDescending(e => e.EventDate)

But when I ran the code, I got an exception because I was using the .Date property of DateTime - basically EF did not know what to do here to convert this into a query. So after some research I found EntityFunctions.TruncateTime. This worked like a charm:

var events = this.coreDomainContext.Events.Where(
    e => EntityFunctions.TruncateTime(e.EventDate.Value) >= DateTime.Today
      && EntityFunctions.TruncateTime(e.EventDate.Value) <= EntityFunctions.TruncateTime(endPeriod))
    .OrderByDescending(e => e.EventDate)

EntityFunctions contains a ton of methods for working with EF entities, have a look through what’s on offer as it could save you from rolling your own EF hacks!

.NET DLL’s Duplicated In Memory–Update

A couple of years ago, I blogged about my findings after analysing the memory usage of RSS Bandit using VMMap. I found that numerous .NET assemblies were appearing twice in the virtual memory region of RSS Bandit and that this behaviour was a known issue to Microsoft. Well if you have a look at the Microsoft Connect page for this issue, you’ll spot that as of .NET 4.0 this issue has been resolved. I’m yet to perform any analysis myself on .NET 4.0 applications, to check if duplication of assemblies has been eradicated, but still, it’s nice to see that this has been resolved.

ASP NET MVC 3 Futures

If you're curious about some of the ideas that could come up in future versions of ASP NET MVC, then check this page. You will find examples of ideas such as:

- dynamic view pages.
- New ActionResults like AtomFeedActionResult.
- HTML helpers such as HTML.Button() and HTML.SubmitButton() (Finally :)

There is a ton of information available on that page, well worth a look.

Remember, there is a roadmap page for ASP NET MVC 4 which illustrates what the team are officially planning for the next release. If you would like to suggest a feature/improvement, then visit the ASP NET user voice page.