Search code examples
c#linqlinq-to-entitiesfunc

How do I use func in Linq to Entity select?


I want a usage like the following, but it gives error if I don't use AsEnumerable. Why I want it because I'm going to need it in many places.

Is there another way to do this?

public static class EntityHelper
{
    public static Func<TABLE1, TABLE2, TABLE2, string> SelectTitle = (trn, acc, parentAcc) => trn.master_id != trn.parent_id ? parentAcc.name : acc.name;
}
 var query = from trn in context.TABLE1
      join acc in context.TABLE2 on trn.acc_id equals acc.id
      join parentAcc in context.TABLE2 on trn.parent_id equals parentAcc.id                            
      select new {name = EntityHelper.SelectTitle.Invoke(trn,acc,parentAcc)};

System.NotSupportedException: 'LINQ to Entities does not recognize the method 'System.String Invoke(TABLE1, TABLE2,TABLE2)' method, and this method cannot be translated into a store expression.'


Solution

  • I solved this work using LinqKit nuget. I changed my code as follows.

    public static class EntityHelper
    {
         public static Expression<Func<TABLE1, TABLE2, TABLE2, string>> SelectTitle = (trn, acc, parentAcc) => trn.master_id != trn.parent_id ? parentAcc.name : acc.name;
    }
    
     var query = from trn in context.TABLE1.AsExpandableEF()
          join acc in context.TABLE2 on trn.acc_id equals acc.id
          join parentAcc in context.TABLE2 on trn.parent_id equals parentAcc.id                            
          select new {name = EntityHelper.SelectTitle.Invoke(trn,acc,parentAcc)};