简体   繁体   中英

EF Core client evaluation doesn't work, when top most projection contains method call

The documentation says that it is OK to have some code which can not be translated to SQL, in the last call to Select :

In EF Core 3.0, we've restricted client evaluation to only happen on the top-level projection (essentially, the last call to Select()). When EF Core 3.0 detects expressions that can't be translated anywhere else in the query, it throws a runtime exception.

Though I'm using a method call just in the last call to Select() , I'm getting a System.InvalidOperationException exception complaining that:

The LINQ expression... could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

I can have my code work, if I write it this way:

// this query works find and gets evaluated well
from entity in DbContext.DbSet<MyEntity>
where <... some conditions ... >
select new EntityDto() 
{
    Prop1 = entity.X.Y,
    Prop2 = someMethod(entity.Z.T),
    Prop3 = <some value>,
    ...
    Prop4 = <some value>,
}

The select clause in the above LINQ query is a long code, so I decided to move it to another separate private method in order to have a more readable code. I expected this to work due to what the documentation says:

// this is the code that gets exception at runtime:
from entity in DbContext.DbSet<MyEntity>
where <... some conditions ... >
select CreateDto(entity.X, entity.Z)

Code snippet above get the exception I told. How can I solve this? Why is EF complaining about client evaluation?

Though I'm using a method call just in the last call to Select(),

Sorry, but "disabled" is "disabled", NOT "disabled, except if you use it in the last call to Select".

Do NOT call the method. Wrap what you get then into an AsEnumerable, THEN (in the enumeration) project and call the method. Done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM