tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Model Defined Function as a method on entity (or on type for store function)

11 Oct 2009 2 mins Entity Framework, Entity SQL, LINQ

Model Defined functions are new feature in EFv4. You simply define you function using EDM functions etc. in your model and then you can use it in your queries. With EdmFunction attribute you can also create stub function to use it in LINQ queries. That’s all great, and even itself makes life with Entity Framework easier.

But if you call it from LINQ (my favourite  way of querying), it’s kind of odd. You’re writing it as:

context.Persons2.Where(p => GetAge2(p) < 100);

And while I was preparing some demos for my presentation, there was a flash of idea in my head. “What if I define the function stub as extension method?", I thought. Yes like:

[EdmFunction("testovaciModel", "GetAge2")]
static int GetAge2(this Persons2 p)
{
	throw new NotSupportedException();
}

This should work, right? It’s just sugar and the translation should work without complaining. And it really does. You can now write:

context.Persons2.Where(p => p.GetAge2() < 100)

Sweet! You can still keep these MDF method stubs in one place but use it in more natural syntax.

And by the way, it works for store functions as well (you’re just limited on types).

[EdmFunction("testovaciModel.Store", "GetAge")]
static int GetAge(this DateTime born)
{
	throw new NotSupportedException();
}
context.Persons2.Where(p => p.Born.GetAge() < 100)

I’m especially happy for store function exposed to LINQ. I’m using these in a reasonable amount in my databases and being able to filter using the function without wrapping the query into i.e. stored procedure or view is neat.

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.