Databases Reference
In-Depth Information
CustomQueryAttribute
CustomQueryAttribute
is another attribute you can find in the
Unleashed.DataAnnotations
project in the sample solution accompanying this topic. It enables you to implement limited
row-level security at the entity class level. The code snippet that follows illustrates how to
use this attribute to allow users in
Customer
role to see only their own Customer records:
[
CustomQuery
(typeof(Customer), “
GetQueryable
”)]
partial class Customer
{
public static IQueryable
GetQueryable
(IQueryable query)
{
IPrincipal user = Thread.CurrentPrincipal;
if (user.IsInRole(“Customer”))
{
query = query.Cast<Customer>().Where(
customer => customer.EmailAddress == user.Identity.Name);
}
return query;
}
}
Similar to the built-in
CustomValidationAttribute
discussed in detail back in Chapter 8,
the
CustomQueryAttribute
takes two parameters—name of a static “
GetQueryable
”
method and the type where it is implemented. This method is similar to the
GetQueryable
method used by the dynamic filter templates and the
GetQueryable
method implemented
in the
UnleashedMetaTable
class earlier. It takes an entity query as a parameter and modi-
fies it based on the permissions of the current user. In this example, the
GetQueryable
method adds a where clause, filtering out customer records that the current user should
not be able to access.
Implementation of the
CustomQueryAttribute
is quite simple. Aside from the constructor,
the main API of this attribute is the
GetQueryable
method, which uses reflection to invoke
the actual method specified in the arguments of the attribute's constructor:
[AttributeUsage(AttributeTargets.Class)]
public class CustomQueryAttribute: Attribute
{
public CustomQueryAttribute(Type type, string method);
public IQueryable
GetQueryable
(IQueryable source);
}
Implementing MetaTable.GetQuery with CustomQueryAttribute
You can take advantage of the
CustomQueryAttribute
when implementing the
GetQuery
method of the
MetaTable
class. The code snippet that follows illustrates how this was