tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Custom logic in every Entity Framework’s query

11 Dec 2011 1 mins Entity Framework, Entity SQL

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.

image

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).

image

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.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.