-1

I have a rather theoretical issue with Entity Framework Core on SQLite. I have an entity - Person { ID, FirstName, LastName, ... }, class PersonReference { ID, Representation : string }, extension method with argument of type Person that composes reference out of Person like this:

public static PersonReference ComposeReference(this Person from) => new PersonReference
            {
                ID = from.ID,
                Representation = from.FirstName + " " + from.LastName
            };

I need to compose references on the sql side. So I do the following:

var result = dbContext.People.Select(p => p.ComposeReference());

Result is IQueriable and program goes beyond that line and materializes the collection successfully. But when I look at the query I see it selects everything of Person and then query text ends.

If I rewrite EF expression to direct

    var result = dbContext.People.Select(p => new PersonReference 
    {
                    ID = from.ID,
                    Representation = from.FirstName + " " + from.LastName
    });

it gives me the satisfying expression with compact select and string concatenations.

Is there a way to keep the composition logic in extension method but still do calculations on the SQL side?

1 Answers1

0

The trick is about using System.Linq.Expressions.Expression. I met it at work and didn't get what it was for at first, but it is designed right for the purpose I required. Declaration:

Expression<Func<Person, PersonReference>> ComposeReference => from => new 
             PersonReference
             {
                ID = from.ID,
                Representation = from.FirstName + " " + from.LastName
             };

Usage:

var result = dbContext.People.Select(ComposeReference);

Pay attention, that expressions can be compiled, but for this case never do it, or it will treat your DbSet as IEnumerable.

The answer from Svyatoslav's comment referred to some libraries, but I think vanilla EF does well enough on its own.