SapphireDb logo SapphireDb

Server - Query function

If you want to restrict the data of a collection a user can query you have to options.
You could add the [QueryAuth] attribute to the model-class. This will lead to one problem. The values first will be queried from the database and then the check is made for every value.
To improve performance you can also use [QueryFunction]. This attribute has to reference a static function in your model, that returns a boolean lambda expression. This expression is then used in the query and executed in the database directly.

Example

You can use dependency injection for the method. SapphireDb will provide you a HttpInformation-object with information about the request and the instances found in the DI-Container.
\f:(csharp:Message.cs) [QueryFunction("QueryFunction")]\n public class Message\n {\n \tpublic static Expression<Func<Message, bool>> QueryFunction(HttpInformation context)\n \t{\n \t\tstring userId = context.User.Claims.FirstOrDefault(cl => cl.Type == "Id")?.Value;\n\n \t\tif (string.IsNullOrEmpty(userId))\n \t\t{\n \t\t\treturn (m) => false;\n \t\t}\n\n \t\treturn (m) => m.UserId == userId || m.ToId == userId;\n \t}\n\n \tpublic string UserId { get; set; }\n\n \tpublic string ToId { get; set; }\n\n \tpublic string Content { get; set; }\n\n }

This website uses Google Analytics. If you want to disable it just unselect the option: