Thursday, October 6, 2011

Linq-to-Entities: EntityFunctions

Jefe: I have put many beautiful methods in the System.Data.Objects.EntityFunctions class, each of them filled with little suprises.
El Guapo: Many methods?
Jefe: Oh yes, many!
El Guapo: Would you say I have a plethora of methods?
Jefe: A what?
El Guapo: A *plethora*.
Jefe: Oh yes, you have a plethora.
El Guapo: Jefe, what is a plethora?
Jefe: Why, El Guapo?
El Guapo: Well, you told me I have a plethora. And I just would like to know if you know what a plethora is. I would not like to think that a person would tell someone he has a plethora, and then find out that that person has *no idea* what it means to have a plethora.
Jefe: Forgive me, El Guapo. I know that I, Jefe, do not have your superior intellect and education. But could it be that once again, you are angry at something else, and are looking to take it out on me?

I ran across this class while attempting some date comparisons with Linq-to-Entities. See, EF won't let you do this:

var orders = db.Orders.Where(order => order.CreatedOn.Date >= model.CreatedOnStart.Date);

It barfs during runtime with "The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.". But with EntityFunctions, we can still get what we need:

var orders = db.Orders.Where(order => EntityFunctions.TruncateTime(order.CreatedOn) >= EntityFunctions.TruncateTime(model.CreatedOnStart));

Handy indeed.

No comments:

Post a Comment