环境:EF6 + Code First
我希望能够在LINQ查询的Where子句中调用自定义函数
所以这一行:
var activeStaff = Repo.Staff.Where(s => s.EndDate == null || s.EndDate.Value > DateTime.Today);
变为:
var activeStaff = Repo.Staff.Where(s => MyEdmFunctions.IsCurrentStaff(s));
这就是我尝试过的,
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new MyCustomConvention());
}
}
public class MyCustomConvention : IConceptualModelConvention<EdmModel>
{
public void Apply(EdmModel item, DbModel model)
{
var boolType = PrimitiveType.GetEdmPrimitiveType(PrimitiveTypeKind.Boolean);
var staffType = item.EntityTypes.Single(e => e.Name == "Staff");
var payLoad = new EdmFunctionPayload
{
ParameterTypeSemantics = ParameterTypeSemantics.AllowImplicitConversion,
IsComposable = true,
IsNiladic = false,
IsBuiltIn = false,
IsAggregate = false,
IsFromProviderManifest = true,
Parameters = new[] { FunctionParameter.Create("Staff", staffType, ParameterMode.In) },
ReturnParameters = new[] { FunctionParameter.Create("ReturnType", boolType, ParameterMode.ReturnValue) }
};
var function = EdmFunction.Create("IsCurrentStaff", "My.Core.Data", DataSpace.CSpace, payLoad, null);
item.AddItem(function);
}
}
public static class MyEdmFunctions
{
[DbFunction("My.Core.Data", "IsCurrentStaff")]
public static bool IsCurrentStaff(Staff s)
{
return s.EndDate == null || s.EndDate > DateTime.Today;
}
}
但我得到&#34;不支持指定的方法。&#34;来自EntityFramework的内部CTreeGenerator类的错误(反编译后)
public override DbExpression Visit(NewRecordOp op, Node n)
{
throw new NotSupportedException();
}
有人可以确认是否真的无法在where子句中调用自定义函数吗?
我知道可以创建存储过程并将其映射到模型中。但有没有办法用C#编写它?
感谢。
答案 0 :(得分:0)