Custom logic in every Entity Framework's query

Few days ago there was a question on Twitter in #efhelp about adding custom logic to every query in Entity Framework. It's pretty easy and you can do it absolutely transparently so nobody using your code needs to know.

First you need to focus you Entity Set (not Entity Type) in Model Browser window.

Here set the access modifier to i.e. private or (internal/protected) and rename it to something else, so it'll not interfere with original name of property we're going to create. I often use X prefix (especially for properties on entities).

Now it's pretty easy to create some logic. Here I simply added filtering to always only fetch entities younger than 10 days from now.

partial class Model1Container
{
	public IQueryable<FooBarEntity> FooBarEntitySet
	{
		get
		{
			DateTime d = DateTime.UtcNow.AddDays(-10);
			return XFooBarEntitySet.Where(fb => fb.Created > d);
		}
	}
}

And that's it. Not a difficult task. But also note that through Entity SQL (or i.e. reflection) somebody might be still able to access original entity set and get access to the data. So it's not rock hard security solution.