efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Support for navigation references in model-level query filters

Open pauldalyii opened this issue 9 years ago • 1 comments

I would like to be able to use navigation references in model-level query filters. This limitation is called out in the ef core / what's new documentation.

I can probably best describe my use case by extending the tenant sample shown in that documentation.

Unlike the referenced sample, I do not have reference to the TenantId foreign key at the time of context creation, therefore I can not reference it in the HasQueryFilter method.

At the time of context creation, I do have reference to another unique property of a tenant: TenantName . (e.g.: "tenant.onmicrosoft.com")

Here is an example of the model:

public class Tenant
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Blog> Blogs { get; set; }
}
public class Blog
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public Tenant Tenant { get; set; }
    public Guid TenantId { get; set; }
    ...
}

In OnModelCreating, I can filter the Tenant entity on a private property _tenantName:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Tenant>().Property(t => t.Name).IsRequired();
    modelBuilder.Entity<Tenant>().HasAlternateKey(t => t.Name);
    modelBuilder.Entity<Tenant>().HasQueryFilter(t => t.Name == _tenantName);
    ...
}

I need to filter a number of other entities by Tenant, and those entities only directly reference the Tenant via a foreign key: TenantId. I'd like to be able use the navigation reference "b.Tenant.Name" in the following manner:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    ...
    modelBuilder.Entity<Blog>().HasQueryFilter(b => b.Tenant.Name == _tenantName);
    ...
}

I think this is important because the value of a filter applied in OnModelCreating is to not have to remember to filter anywhere else. As it is implemented currently, I still need to pay attention anytime I interact with something other than the Tenant model.

pauldalyii avatar Aug 23 '17 18:08 pauldalyii

duplicate of #8881

smitpatel avatar Aug 23 '17 21:08 smitpatel