2014-06-18 130 views
0

ENV:EF6 +代碼首先調用自定義函數Where子句

我希望能夠調用自定義函數的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; 
    } 
} 

但是我得到了「不支持指定的方法」。錯誤從的EntityFramework的內部CTreeGenerator類(編譯後)

public override DbExpression Visit(NewRecordOp op, Node n) 
    { 
     throw new NotSupportedException(); 
    } 

可有人請確認是否真的沒有方法來調用在where子句中的自定義函數?

我知道可以創建一個存儲過程並將其映射到模型中。但有沒有辦法用C#編寫它?

謝謝。

回答