I want to be able to filter all POCO’s that implement the iaudit interface so that a user can only possibly access the records they created. I looked through the docs and didn’t see anything.
I don’t know what you mean, please provide some example code.
Sure, see the below code as an example. I am fairly certain this is from the OrmLite docs.
//filter out is deleted records
OrmLiteConfig.SqlExpressionSelectFilter = q =>
{
if (q.ModelDef.ModelType.HasInterface(typeof(ISoftDelete)))
{
q.Where<ISoftDelete>(x => x.IsDeleted != true);
}
};
I would like to do something similar with an IAudit interface
public interface IAudit
{
int Id { get; set; }
string CreatedBy { get; set; }
DateTime DateCreated { get; set; }
string ModifiedBy { get; set; }
DateTime? DateModified { get; set; }
bool IsDeleted { get; set; }
}
So that I could grab the user’s auth id and automatically filter the result set if the model has the IAudit interface.
This is a static query filter, you don’t have access to any instances, only its ModelDefinition (q.ModelDef
).
So you can check whether the Query Expression Type (i.e. SqlExpression<T>
) has a UserAuthId with:
if (q.ModelDef.GetFieldDefinition("UserAuthId") != null)
{
//..
}
But you can’t access the instances value, because there is no instance, this static filter is used to customize the query expression before its executed, it does not have the results of the query after its executed.
It only has access to the Type
q.ModelDef.ModelType
and Table Definition q.ModelDef
.
And I would assume there is no way to get session information as well. It was worth a try.
It’s a static handler to be initialized once on Startup, it doesn’t have access to any per-request context itself, only if the request context was made statically available on the HTTP request worker thread that invokes the callback.
Historically this is only possible in classic ASP .NET Framework (via its HttpContext.Current
singleton) which you can access from:
var req = HostContext.AppHost.TryGetCurrentRequest();
It’s disabled in .NET Core by default due to performance, but you can opt-in to make singleton Request Context available with:
This is still only available if the callback is invoked from the HTTP Request Worker Thread. Personally I wouldn’t rely and try to access the Request Context via a singleton, I’d have Services call a generic API that passes in the base.Request
context or Session Information in from the Service.