Home > Enterprise >  LinqKit pass variable into Expression
LinqKit pass variable into Expression

Time:12-13

I'm trying to pass a variable from the outer context into an expression which is built with LinqKit's expression expanding.

I'm getting the following exception:

variable '__name_0' of type 'System.String' referenced from scope '', but it is not defined|System.InvalidOperationException: variable '__name_0' of type 'System.String' referenced from scope '', but it is not defined.

public static class EntityProjections
{
    public static Expression<Func<Entity, Model>> GetModelProjection(string name)
    {
        return entity => new Model()
        {
            Id = entity.Id,
            Name = entity.Name != name ? entity.Name : null
        };
    }
}

string name = "Test";

var models = dbContext.Entities.Select(entity => EntityProjections.GetModelProjection(test).Invoke(entity)).ToList();

Is it possible to pass a variable like this from outside, to build the desired query?

CodePudding user response:

You need expression substitution here. It can be done by ExpandableAttribute:

public static class EntityProjections
{
    [Expandable(nameof(GetModelProjectionImpl))]
    public static Model GetModelProjection(Entity entity, string name)
    {
        throw new NotImplementedException(); // should not call
    }

    // static function without parameters
    private static Expression<Func<Entity, string, Model>> GetModelProjectionImpl()
    {
        return (entity, name) => new Model()
        {
            Id = entity.Id,
            Name = entity.Name != name ? entity.Name : null
        };
    }
}

Sample call will be:

string name = "Test";

var models = dbContext.Entities
   .Select(entity => EntityProjections.GetModelProjection(entity, name))
   .ToList();
  • Related