0
var item = Db.BuyFactorWithTag.Where(b =>
     !b.IsSell && SearchUtility.SearchPersonByName(MR_SANAD_BASE , b.FK_Seller , input)).ToList();

public static bool SearchPersonByName(MrSanadBaseDb.Entities db, long? id, string input)
{
      id = id ?? 0;
      return db.Person.FirstOrDefault(p => p.PK_Person == id && !p.IsDeleted && p.FullName.Contains(input)) != null;
}

I have SearchByPersonName in many places and turned it into a method, but Linq does not allow me to run it and gives me this error. How can I fix this error?

Error text

LINQ to Entities does not recognize the method 'Boolean SearchPersonByName(MrSanadBaseDb.Entities, System.Nullable`1[System.Int64], System.String)' method, and this method cannot be translated into a store expression.

2 Answers2

1

The answer to this can be found here.

Entity Framework uses Expressions so it can read the syntax of the LINQ content and tries to convert it into sql. C# method calls are not something that it convert into sql. If you want to look more into this, you can do some reading here

KingOfArrows
  • 556
  • 2
  • 11
  • Can you help with the code that only turns this **SearchByPerson** code into Expression? –  Apr 11 '20 at 08:05
  • Hey @Mohammad. It might be a better approach to not rely on using the code in the method `SearchPersonByName` and instead update your where clause to handle the logic you want to achieve. Using LINQ you can do a join onto the Person table where Person.PK_Person = BuyFactorWithTag.FK_Seller. Then in the where clause you can check where person is not deleted and if the name contains the `input` variable. – KingOfArrows Apr 11 '20 at 08:19
0

As @KingOfArrows mentioned, your SearchByPerson method can not be translated so you need to write this method into Expression. Moreover, Entity Framework allows you to write sub-queries within same context.

So that you can write LINQ as follow:

var item = Db.BuyFactorWithTag.Where(b =>
     !b.IsSell && 
     DB.Person.Any(p =>  p.PK_Person == (b.FK_Seller.HasValue ? b.FK_Seller.Value : 0) && !p.IsDeleted && p.FullName.Contains(input))).ToList();
Selim Yildiz
  • 5,254
  • 6
  • 18
  • 28