Search code examples
c#linq-to-entitiesexpression-trees

using Linq.Expressions.Expression to assign value to struct within larger select clause


if I have an expression to minimise code reuse (much more complex than that below, but being used for demonstration)

internal static Expression<Func<IParticipant, bool>> Is28Expression(DateTime? dt28Prior=null)
{
    DateTime twentyEightPrior = dt28Prior ?? DateTime.Now.AddDays(-28);
    return p => p.DOB >= twentyEightPrior
}

is it possible to run the expression against the database as part of a larger select clause? I am trying to achieve something like the following (pseudocode not written to build)

var is28 = ParticipantBaseModel.Is28Expression();
return new ParticipantsSummary(_dbContext.Participants.Select(p => 
                                new ParticipantStage 
                                { 
                                    Id = p.Id, 
                                    Arm = p.TrialArm,
                                    Is28 = is28(p)
                                }));

Solution

  • Answer was to use LinqKit

    var is28 = ParticipantBaseModel.Is28Expression();
    return new ParticipantsSummary(from p in _dbContext.Participants.AsExpandable()
                                   select new ParticipantStage 
                                   { 
                                      Id = p.Id, 
                                      Arm = p.TrialArm,
                                      Is28 = is28.Invoke(p)
                                   }));