koenbeuk / EntityFrameworkCore.Projectables

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

Lambda operator #45

Closed yudielcurbelo closed 1 year ago

yudielcurbelo commented 1 year ago

Hi,

I have a question regarding how the library works.

This code works using the lambda operator.

 [Projectable]
 public static int GetTransactionType(this Transaction transaction) => 1;

This code does not work using the normal body return.

[Projectable]
public static int GetTransactionType(this Transaction transaction)
{
    return 1;
}

error EFP0001: Method or property 'GetTransactionType' should expose an expression body definition

koenbeuk commented 1 year ago

That error is correct. This library works by creating a companion expression of the arrow function, e.g.:

 [Projectable]
 public static int GetTransactionType(this Transaction transaction) => 1;

will generate:

public static Expression<Func<Transaction, int>> GetTransactionType => 1;

which is valid C#, unlike:

public static Expression<Func<Transaction, int>> GetTransactionType { return 1; }
yudielcurbelo commented 1 year ago

Thank you.

Below is the solution that I'm currently using.

[Projectable]
public static int GetTransactionType(this Transaction transaction) => GetTransactionTypeInternal(transaction);
public static int GetTransactionTypeInternal(Transaction transaction)
{
    ... code
}

Note: GetTransactionTypeInternal cannot be a private method.

koenbeuk commented 1 year ago

This solution is invalid as it's calling into a non-projectable member. This solution is essentially the same as writing:

query.Select(x => GetTransactionTypeInternal(x)) 

which will cause EF to switch to client side evaluation. Consider rewriting GetTransactionTypeInternal with an arrow function or if not possible, a database function that can compute this value.

yudielcurbelo commented 1 year ago

Thank you for your detailed explanation. I was trying to add some logic about the entity types that need to contain a method body.