Currently model defined functions cannot be created using Code First model conventions. Unblocking this would enable such things as @moozzyk's [Code First Functions](https://codefirstfunctions.codeplex.com/) project to defined model defined functions, as explained in the comments in [#2485](http://entityframework.codeplex.com/workitem/2485).
I started digging into why this is blocked with the following convention that attemps to produce a (not very useful) model defined function:
```
public class StuffFunctionInjectionConvention :
IConceptualModelConvention<EdmModel>
{
public void Apply(EdmModel item, DbModel model)
{
FunctionParameter parameter = FunctionParameter.Create(
"birthDate",
PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.DateTime),
ParameterMode.In);
FunctionParameter returnValue = FunctionParameter.Create(
"result",
PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Int32),
ParameterMode.ReturnValue);
EdmFunction function = item.CreateAndAddFunction(
"GetAge",
new[] {parameter},
new[] {returnValue},"SELECT 5"); // TODO: calculate
}
}
public static class DbMetadataExtensions
{
public static EdmFunction CreateAndAddFunction(this EdmModel item, string name,
IList<FunctionParameter> parameters, IList<FunctionParameter> returnValues, string body = null)
{
var payload = new EdmFunctionPayload
{
StoreFunctionName = name,
Parameters = parameters,
ReturnParameters = returnValues,
Schema = item.GetDefaultSchema(),
CommandText = body
};
EdmFunction function = EdmFunction.Create(
name,
item.GetDefaultNamespace(),
item.DataSpace, payload,
null);
item.AddItem(function);
return function;
}
public static string GetDefaultNamespace(this EdmModel layerModel)
{
return layerModel
.GlobalItems
.OfType<EdmType>()
.Select(t => t.NamespaceName)
.Distinct()
.Single();
}
public static string GetDefaultSchema(this EdmModel layerModel)
{
return layerModel
.Container
.EntitySets
.Select(s => s.Schema)
.Distinct()
.SingleOrDefault();
}
}
```
The first thing I hit is the following validation errors:
Schema specified is not valid. Errors:
(0,0) : error 0005: The 'Aggregate' attribute is not allowed.
(0,0) : error 0005: The 'BuiltIn' attribute is not allowed.
(0,0) : error 0005: The 'NiladicFunction' attribute is not allowed.
(0,0) : error 0005: The 'IsComposable' attribute is not allowed.
(0,0) : error 0005: The 'ParameterTypeSemantics' attribute is not allowed.
(0,0) : error 0005: The 'Schema' attribute is not allowed.
(0,0) : error 0005: The 'Mode' attribute is not allowed.
Furthermore, the DefiningExpression element that is required for model defined functions is currently not honored by the EDM serialization code (e.g. in EdmModelVisitor & EdmSerializationVisitor; historically neither Code First nor the EF Designer used them).