koenbeuk / EntityFrameworkCore.Projectables

Project over properties and functions in your linq queries
MIT License
297 stars 20 forks source link

Using constants instead of literals in property expressions #21

Closed beercsaba closed 2 years ago

beercsaba commented 2 years ago

Hi,

i'd like to add a new property to Product class in model of BasicSample: [Projectable] public bool IsExpensive => Price > Consts.ExpensiveThreshold; where Consts is: public static class Consts { public static readonly double ExpensiveThreshold = 0; }

query: var query = dbContext.Products.Select(x => new { x.IsExpensive }); generated sql query: SELECT "p"."Price" FROM "Products" AS "p" LIMIT 1

query like this cannot be translated: dbContext.Products.Where(p => p.IsExpensive).Select(x => new { x.Name });

When i use literals in the expression of the property (eg. public bool IsExpensive => Price > 2;) translation works perfectly: SELECT "p"."Price" > 2.0 AS "IsExpensive" FROM "Products" AS "p" and SELECT "p"."Name" FROM Products" AS "p" WHERE "p"."Price" > 2.0

Is there any smart way to solve this issue?

Thanks, Csaba

koenbeuk commented 2 years ago

Thanks for reporting this!

The issue seems to be related to constant folding with limited the limited compatibility mode (default). I will have to dive deeper into this.

For now, you can enable full compatibility mode globally- or manually expand projectables in your queries where you access the Const class,

e.g.:

using EntityFrameworkCore.Projectables.Extensions;

dbContext.Set<Entity>()
  .Where(x => x.IsExpensive)
  .ExpandProjectables() // This forces full compatibility mode for this query
  .ToList();
beercsaba commented 2 years ago

I will try this "quick and dirty workaround" and i hope You will be able to find the real solution! :)

beercsaba commented 2 years ago

I have to use version 1.0.1 on .NET 5. i've tried the workaround with ExpandQuaryables(), but it fails. So i must wait...

beercsaba commented 2 years ago

Thank You!