ReSharper 2023.3 Help

Code Inspection: Database function must not be called in non-database context

This problem is reported if you attempt to call a method that is meant to be executed in the database (typically as part of a LINQ to Entities query) outside of that context.

For instance, Entity Framework provides several methods intended for use within LINQ to Entities queries, such as EF.Functions.Like() and EF.Functions.DateDiffDay(). These methods do not have any meaningful implementations and serve as markers for Entity Framework to translate them into corresponding SQL functions or statements.

When called outside a LINQ to Entities query, there is no longer a query to translate into SQL, and instead these methods will get executed as .NET methods, which is meaningless and likely an error.

To resolve this problem, make sure that such methods are only called within a LINQ query that is translated into SQL by Entity Framework.

In the example below, the use EF.Functions.Like() outside of a LINQ to Entities query context is problematic. To fix it, we put the EF.Functions.Like() call inside a LINQ to Entities query.

var context = new MyDbContext(); string pattern = "John%"; bool isJohn = EF.Functions.Like("John Doe", pattern);
var context = new MyDbContext(); string pattern = "John%"; bool isJohn = context.Customers.Any(c => EF.Functions.Like(c.Name, pattern));
Last modified: 28 November 2023