Expression Tree in extension method will be evaluated locally

c# entity-framework entity-framework-core expression

Question

I would like to add the TenantId to the Asp.Net Identity tables (e.g.: User).

The following snippet works fine. The tenant context will be injected via DI and the tenant change depending on the http context domain:

private readonly ITenantContext<ApplicationTenant> tenantContext;

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options, ITenantContext<ApplicationTenant> tenantContext) : base(options)
{
    this.tenantContext = tenantContext;
}

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>(b =>
    {
        // add tenant
        b.Property(typeof(int), "TenantId");
        b.HasQueryFilter(x => EF.Property<int>(x, "TenantId") == this.tenantContext.Tenant.Id);
    });
}

For reuse I want to create an extension method for the entityBuilder:

public static class EntityTypeBuilderExtensions
{

    public static void AddTenancy<TEntity>(
        this EntityTypeBuilder<TEntity> builder,
        Expression<Func<int>> tenantId,
        string propertyName = "TenantId")
        where TEntity : class
    {
        // validate
        Ensure.Argument.NotNull("builder", builder);

        // add property to entity
        builder.Property(typeof(int), propertyName).IsRequired();


        /* THIS WORKS BUT WILL BE EVALUATED LOCALLY */
        // left
        var parameterExp = Expression.Parameter(typeof(TEntity), "x"); // e = TEntity => e.g: User
        var propertyNameExp = Expression.Constant(propertyName, typeof(string)); // the name of the tenant column - eg.: TenantId
        // right
        var tTenantId = Expression.Convert(tenantId.Body, typeof(int));  // tenantId
        var propertyMethod = typeof(EF).GetMethod(nameof(EF.Property), BindingFlags.Public | BindingFlags.Static).MakeGenericMethod(typeof(int)); // build EF.Property
        var propertyMethodExec = Expression.Call(propertyMethod, parameterExp, propertyNameExp);  // represents EF.Property(e, "TenantId")
        var bodyExp = Expression.Equal(propertyMethodExec, tTenantId);
        var lambda = Expression.Lambda(bodyExp, parameterExp);
        builder.HasQueryFilter(lambda);
    }
}

And in the db context:

private Func<int> tenantId => () =>
{
    // return tenant id
    if (this.tenantContext != null && this.tenantContext.Tenant != null)
    {
        return this.tenantContext.Tenant.Id;
    }

    return -1;
};

protected override void OnModelCreating(ModelBuilder builder)
{
    base.OnModelCreating(builder);

    builder.Entity<ApplicationUser>(b =>
    {
        b.AddTenancy(() => this.tenantId(), "TenantId");
    });
}

The extension method works also fine but the expression is evaluated locally :-(. Can someone help me to fix it?

The LINQ expression 'where (Property([x], "TenantId") == Invoke(__ef_filter__tenantId_0))' could not be translated and will be evaluated locally. The LINQ expression 'where ([x].NormalizedUserName == __normalizedUserName_0)' could not be translated and will be evaluated locally. The LINQ expression 'FirstOrDefault()' could not be translated and will be evaluated locally.

1
4
12/18/2018 7:18:03 PM

Accepted Answer

The problem is the Func here

private Func<int> tenantId => ...

which is causing a bad translation Invoke(__ef_filter__tenantId_0)) and client evaluation.

The solution is to make tenantId simple int returning property or method. For instance, to keep the calls

b.AddTenancy(() => this.tenantId(), "TenantId");

it should be changed to

private int tenantId()
{
    // return tenant id
    if (this.tenantContext != null && this.tenantContext.Tenant != null)
    {
        return this.tenantContext.Tenant.Id;
    }

    return -1;
};
1
12/19/2018 7:43:28 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow