我可以为每个会话使用单独的查询计划缓存吗?

Can I use a separate query plan cache per session?

我有一个多租户 ASP.NET 应用程序,我们的数据库设置了软删除。最初,我们直接在查询级别处理数据的限制,例如:

var foos = context.Foos.Where(foo => !foo.Deleted && foo.TenantId = currentTenantId).ToList();

如您所想,这会使我们的数据访问层中的所有查询膨胀,如果忘记添加正确的过滤条件,API 将变得非常脆弱。我们已决定将全局过滤应用于 Z.EntityFramework.Plus.EF6:

的上下文
public class FooDataContextFactory
{
    public FooDataContext CreateContext()
    {
        var context = new FooDataContext();

        context.Filter<Foo>(collection => collection.Where(foo=> !foo.Deleted));

        var principal = Thread.CurrentPrincipal as ClaimsPrincipal;
        if (principal.HasClaim(claim => claim.Type == "TenantId"))
        {
            var currentTenantId = int.Parse(principal.FindFirst("TenantId").Value);
            context.Filter<Foo>(collection => collection.Where(foo => foo.TenantId == currentTenantId));
        }

        return context;
    }
}

这非常适合单个用户。但是,当您切换租户时,我们遇到了将过滤器表达式保存在 the query plan cache. This is a known issue 和 Entity Framework Plus 中的问题,并且由于它似乎没有得到解决,我需要找到一个解决方法。

我能想到的最直接的解决方案是将查询计划缓存的生命周期关联到当前会话,当用户注销或切换租户时,缓存被销毁。这可能吗?如果可以,我该如何实现?

我遇到了完全相同的问题,并尝试使用 Z.EntityFramework.Plus.EF6 解决相同的问题。我发现 zzzprojects 团队也有 EntityFramework.DynamicFilters 可以更好地用于此目的。缓存的查询已参数化,并使用您提供的选择器函数在运行时注入值。

using System.Data.Entity;
using EntityFramework.DynamicFilters;

public class Program
{   
    public class CustomContext : DbContext
    {
        private int _tenantId;

        public int GetTenantId()
        {
            return _tenantId;
        }

        // Call this function to set the tenant once authentication is complete.
        // Alternatively, you could pass tenantId in when constructing CustomContext if you already know it
        // or pass in a function that returns the tenant to the constructor and call it here.
        public void SetTenantId(int tenantId)
        {
            _tenantId = tenantId;
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            // Filter applies to any model that implements ITenantRestrictedObject
            modelBuilder.Filter(
                "TenantFilter",
                (ITenantRestrictedObject t, int tenantId) => t.TenantId == tenantId,
                (CustomContext ctx) => ctx.GetTenantId(), // Might could replace this with a property accessor... I haven't tried it
                opt => opt.ApplyToChildProperties(false)
            );
        }
    }

    public interface ITenantRestrictedObject
    {
        int TenantId { get; }
    }
}