Global Query Filters in Entity Framework Core 2.0
With Entity Framework Core 2.0, we now have the ability to introduce global query filters into our code. Learn about what they are, and how and when to use them.
Join the DZone community and get the full member experience.
Join For Freeentity framework core 2.0 introduces global query filters that can be applied to entities when a model is created. it makes it easier to build multi-tenant applications and support soft deleting of entities. this blog post gives a deeper overview of how to use global query filters in real-life applications and how to apply global query filters to domain entities automatically.
sample solution: i built a sample solution efcoreglobalqueryfilters on asp.net core 2 that demonstrates global query filters in a more complex context. it demonstrates some ideas about how to apply global query filters to domain entities automatically. sql-script for creating a simple database and filling it with test data is also there.
what do global query filters look like?
this is how global query filters may look for soft delete. this override for onmodelcreating method of dbcontext class:
protected override void onmodelcreating(modelbuilder modelbuilder)
{
modelbuilder.entity<playlist>().haskey(e => e.id);
modelbuilder.entity<playlist>().hasqueryfilter(e => !e.isdeleted);
modelbuilder.entity<song>().haskey(e => e.id);
modelbuilder.entity<song>().hasqueryfilter(e => !e.isdeleted); base.onmodelcreating(modelbuilder);
}
these filters are applied always when entities of given types are queried.
what do real applications need?
the code above is simplified and doesn’t consider real-life scenarios. when considering mission critical applications that are part of the digital core or enterprises, then there will not just be a couple of classes, although the architecture of applications is often complex. the goal of this post is to demonstrate the following:
- how to support multi-tenancy,
- how to support soft deleting of entities, and
- how to automate detecting of entities.
the sample solution helps to get started with more complex scenarios, but it doesn’t provide a fully flexible and complex framework for this. there are just too many nuances involved when it comes to real-life applications, and every application usually has it’s own set of solutions for different problems.
defining entities
let’s start with defining some entities. they use a simple base class and it is expected that all entities extend from the base class.
public abstract class baseentity
{
public int id { get; set; }
public guid tenantid { get; set; }
public bool isdeleted { get; set; }
}
public class playlist : baseentity
{
public string title { get; set; }
public ilist<song> songs { get; set; }
}
public class song : baseentity
{
public string artist { get; set; }
public string title { get; set; }
public string location { get; set; }
}
now there are some simple entities and it’s time to make next steps towards multi-tenancy and soft deleted entities.
tenant provider
before talking about multi-tenancy, there must be some way for the web application to detect tenants related to the current request. it can be host header based detection, but it can also be something else. this post uses a dummy provider to keep things simple.
public interface itenantprovider
{
guid gettenantid();
} public class dummytenantprovider : itenantprovider
{
public guid gettenantid()
{
return guid.parse("069b57ab-6ec7-479c-b6d4-a61ba3001c86");
}
}
this provider must be registered in configureservices method of startup class.
creating data context
i expect at this point that the database is already created and an application is configured to use it. let’s start with a simple data context that already supports the tenant provider.
public class playlistcontext : dbcontext
{
private guid _tenantid;
private readonly ientitytypeprovider _entitytypeprovider;
public virtual dbset<playlist> playlists { get; set; }
public virtual dbset<song> songs { get; set; }
public playlistcontext(dbcontextoptions<playlistcontext> options,
itenantprovider tenantprovider)
: base(options)
{
_tenantid = tenantprovider.gettenantid();
}
protected override void onmodelcreating(modelbuilder modelbuilder)
{
modelbuilder.entity<playlist>().haskey(e => e.id);
modelbuilder.entity<song>().haskey(e => e.id); base.onmodelcreating(modelbuilder);
}
}
with data context working and tenant id available it’s time to make next step towards automatically created global query filters.
detecting entity types
before adding global query filters for all entity types, the entity types must be detected. it’s easy to read these types if the base entity type is known. there’s one gotcha – the model is built on every request, but it is not a good idea to scan assemblies every time the model is created. so, type detection must support some kind of caching. these two methods go to the data context class.
private static ilist<type> _entitytypecache;
private static ilist<type> getentitytypes()
{
if(_entitytypecache != null)
{
return _entitytypecache.tolist();
}
_entitytypecache = (from a in getreferencingassemblies()
from t in a.definedtypes
where t.basetype == typeof(baseentity)
select t.astype()).tolist();
return _entitytypecache;
}
private static ienumerable<assembly> getreferencingassemblies()
{
var assemblies = new list<assembly>();
var dependencies = dependencycontext.default.runtimelibraries;
foreach (var library in dependencies)
{
try
{
var assembly = assembly.load(new assemblyname(library.name));
assemblies.add(assembly);
}
catch (filenotfoundexception)
{ }
}
return assemblies;
}
warning! architecture-wise, it could be a better idea if there is a separate service that returns entity types. in the code above, it is possible to use entity types variable directly and what’s even worse – it is possible to call getreferencingassemblies method. if you write a real application, then it's better to go with a separate provider.
now the data context knows entity types and it’s possible to write some code to get query filters applied to all entities.
applying query filters to all entities
it sounds like something easy to do, but it’s not. there’s a list of entity types and no way to use convenient generic methods directly. in this point, a little tricking is needed. i found a solution from the codedump page ef-core 2.0 filter all queries (trying to achieve soft delete) . the code there is not usable as it is, as the data context here has instance level dependency to itenantprovider. but the point remains the same: let’s create a generic method call to some generic method that exists in the data context.
protected override void onmodelcreating(modelbuilder modelbuilder)
{
foreach (var type in getentitytypes())
{
var method = setglobalquerymethod.makegenericmethod(type);
method.invoke(this, new object[] { modelbuilder });
}
base.onmodelcreating(modelbuilder);
}
static readonly methodinfo setglobalquerymethod = typeof(playlistcontext).getmethods(bindingflags.public | bindingflags.instance)
.single(t => t.isgenericmethod && t.name == "setglobalquery"); public void setglobalquery<t>(modelbuilder builder) where t : baseentity
{
builder.entity<t>().haskey(e => e.id);
//debug.writeline("adding global query for: " + typeof(t));
builder.entity<t>().hasqueryfilter(e => e.tenantid == _tenantid && !e.isdeleted);
}
it’s not easy and intuitive code. even i stare my eyes out when looking at this code. even when i look at it hundred times it still looks crazy and awkward. the setglobalquery method is also a good place to put defining primary keys for entities, as they all inherit from the same base entity class.
test drive
to try out how global query filters work, it’s possible to use homecontroller of sample application.
public class homecontroller : controller
{
private readonly playlistcontext _context;
public homecontroller(playlistcontext context)
{
_context = context;
}
public iactionresult index()
{
var playlists = _context.playlists.orderby(p => p.title);
return view(playlists);
}
}
i modified default view to display all playlists that query returns.
@model ienumerable<playlist>
<div class="row">
<div class="col-lg-8">
<h2>playlists</h2> <table class="table table-bordered">
<thead>
<tr>
<th>playlist</th>
<th>tenant id</th>
<th>is deleted</th>
</tr>
</thead>
<tbody>
@foreach(var playlist in model)
{
<tr>
<td>@playlist.title</td>
<td>@playlist.tenantid</td>
<td>@playlist.isdeleted</td>
</tr>
}
</tbody>
</table>
</div>
</div>
the web application is now ready for running. here is the sample data i’m using. let’s remember that tenant id used by sample application is 069b57ab-6ec7-479c-b6d4-a61ba3001c86.
when the web application is run, then the following table is shown:
when comparing these two tables, it is easy to notice that the global query filters work and give the expected results.
wrapping up
global query filters are a nice addition to entity framework core 2.0, and until there are not many entities, then it’s possible to go with simple examples given in the documentation. for more complex scenarios, some tricky code is needed to apply global query filters automatically. hopefully there will be some better solution for this in the future, but currently, the solution given here makes excellent work too.
Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments