Comments (7)
Hi @Andreamarcelli, thanks for asking.
The way JADNC works is that the response serializer needs to know which relationships need to be rendered. When using the built-in pipeline (controller/service/repository), this information is automatically derived from the include
query string parameter. To do this manually, inject IEvaluatedIncludeCache
and call its Set
method. To construct its IncludeExpression
parameter, you can inject IIncludeParser
and call its Parse
method that takes a string.
However, if your goal is to support multi-tenancy, we have existing samples for that. See https://github.com/json-api-dotnet/JsonApiDotNetCore/tree/master/src/Examples/DatabasePerTenantExample and https://github.com/json-api-dotnet/JsonApiDotNetCore/tree/master/test/JsonApiDotNetCoreTests/IntegrationTests/MultiTenancy.
from jsonapidotnetcore.
Thanks for the answer.
I've a problem and i not understand how to fix, i paste my code:
ignore the override of the delete and the filter on tenant 999, is only for demo
`{
public class UsersController : JsonApiController<User, String>
{
private IJsonApiManualService _jsonApiManualService;
protected readonly UserManager _userManager;
protected readonly IDocumentService _docService;
private readonly MyDbContext _context;
private IEvaluatedIncludeCache _evaluatedIncludeCache;
private IncludeParser _includeParser;
[ActivatorUtilitiesConstructor]
public UsersController(IJsonApiManualService jsonApiManualService
, IJsonApiOptions options, IResourceGraph resourceGraph
, ILoggerFactory loggerFactory
, IResourceService<User, String> resourceService
, MyDbContext context
, IEvaluatedIncludeCache evaluatedIncludeCache
, IncludeParser includeParser) : base(options, resourceGraph, loggerFactory, resourceService)
{
_jsonApiManualService = jsonApiManualService;
_context = context;
_evaluatedIncludeCache = evaluatedIncludeCache;
_includeParser = includeParser;
}
[HttpDelete("{id}")]
public override async Task<IActionResult> DeleteAsync(String id, CancellationToken cancellationToken)
{
try
{
User ut = await _jsonApiManualService.DeleteUser(id);
if (ut == null)
{
return StatusCode(404);
}
return StatusCode(204);
}
catch (Exception ex)
{
return StatusCode(500, ex.Message);
}
}
[HttpGet]
[Route("statistics")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status401Unauthorized)]
[ProducesResponseType(StatusCodes.Status405MethodNotAllowed)]
[ProducesResponseType(StatusCodes.Status406NotAcceptable)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> Statistics()
{
_evaluatedIncludeCache.Set(_includeParser.Parse("UserTenants", new ResourceType("User",typeof(User), typeof(String)), 10));
var query = _context.Users.Include(u => u.UserTenants).Where(u => u.UserTenants.Any(ut => ut.Tenant.Id == 999));
dynamic users = query.ToList();
return Ok(users);
}
}
}`
the error is:
"Relationship 'UserTenants' does not exist on resource type 'User'."
but inside User i have
[HasMany]
public ICollection UserTenants { get; set; }
from jsonapidotnetcore.
In that case, inject IResourceGraph
and obtain the resource type from it, and then its relationship.
from jsonapidotnetcore.
I don't think ICollection
would work, it should be ICollection<UserTenant>
.
And remove ProducesResponseType
from your controller, OpenAPI won't work.
from jsonapidotnetcore.
Any reason why you can't use one of the fully working samples? It'd save you quite some trouble.
from jsonapidotnetcore.
Thanks for the answer, now works !
how you mean with the "one of the fully working samples" ?
i not found a sample of a custom controller that allow me to write some custom code and return a response in jsonapi format with relationship and other.
i know that i can use the autogenerated crud and use the include in the api call, but for some reason i need to do it in custom way to implement some business logic inside.
from jsonapidotnetcore.
It demonstrates how to set up multi-tenancy using an EF Core HasQueryFilter
in the DbContext
, so tenant filtering works across all queries at all endpoints. See also https://learn.microsoft.com/en-us/ef/core/miscellaneous/multitenancy. If your entire API is tenant-aware, this is the proper way to set it up. If your API isn't, except for this single custom action method, then your approach should be fine.
from jsonapidotnetcore.
Related Issues (20)
- Request with query string '=' returns 500 HOT 3
- cleanupcode.ps1 <revision> fails on Linux HOT 1
- Empty string ID is accepted in post resource request HOT 1
- Clarify usage of explicit controllers
- Add tests for submitting meta
- Look into usage of [BindRequired] HOT 1
- Source generation when models are in a separate project HOT 1
- PrimaryResourceType is null and giving error "Expected IJsonApiRequest.PrimaryResourceType not to be null at this point." HOT 6
- Attempting to setup sample app with filtering and getting error on filtered call. HOT 3
- Differently encoded URLs in self and first links HOT 1
- DateTime in filter expression gets parsed as local DateTime when using "Z" designator HOT 3
- Use IResourceService outside of the path of a request HOT 10
- Multiple db context and keeping single resource HOT 10
- Multiple DbContexts seems to conflict each other at runtime HOT 2
- Customize paging for each controller ? HOT 10
- Support JSONB columns HOT 4
- Attribute unavailable & available if request HOT 7
- TopLevelLinks All / Paging does not work as expected HOT 3
- Use form fields in issue template HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from jsonapidotnetcore.