Where communities thrive


  • Join over 1.5M+ people
  • Join over 100K+ communities
  • Free without limits
  • Create your own community
People
Activity
    taccommandeur
    @taccommandeur
    Hi everyone, I have a question about an error I am getting when trying to include a resource.
    taccommandeur
    @taccommandeur

    When doing a post on an endpoint I get the following error:

    POST: https://localhost:5001/api/v1/students?include=processes

    Response body:

    {
        "errors": [
            {
                "id": "081e90ef-9659-48bd-a08b-f5ea8d9c9a1c",
                "status": "500",
                "title": "An unhandled error occurred while processing this request.",
                "detail": "The LINQ expression 'OUTER APPLY Projection Mapping:\n(\n    SELECT t.Id, t.StudentId, s0.Id AS Id0, s0.Email\n    FROM Projection Mapping:\n    (\n        SELECT TOP(@__Create_Item1_0) p.Id, p.StudentId\n        FROM Processes AS p\n        WHERE t.Id == p.StudentId\n        ORDER BY p.Id ASC\n    ) AS t0\n    INNER JOIN Students AS s0 ON t.StudentId == s0.Id\n) AS t1' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
            }
        ]
    }

    I am trying to debug the error but I am fairly new to .NET. I am guessing I must have something misconfigured somewhere in either the db context or my resource class. But my main problem now is that I don't understand what the error means. Does anyone have any pointers to where I should start looking to fix this?

    taccommandeur
    @taccommandeur

    The weird thing is that in my request body (when I dont do ?include=processes) I am getting relationship links for my resource:

    https://localhost:5001/resource-api/v1/processes/08d930ca-5e91-45c7-8c8f-e4f06ac1a009/student <- this endpoint works
    https://localhost:5001/resource-api/v1/students/08d930bf-1e73-40ba-80da-ab3b24e5298e/relationships/processes <- this link does not work

    To me it looks like the foreign id is found, but the entity is not hydrated.

    taccommandeur
    @taccommandeur
    The response body of POST: https://localhost:5001/api/v1/students?include=processes when I don't [EagerLoad] the related entity is actually:
    {
        "errors": [
            {
                "id": "dd63ec2e-34b4-4af7-bd77-8ee3a4824dd2",
                "status": "500",
                "title": "An unhandled error occurred while processing this request.",
                "detail": "The LINQ expression 'ROW_NUMBER() OVER(PARTITION BY p.StudentId ORDER BY p.Id ASC)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information."
            }
        ]
    }
    Bart Koelman
    @bart-degreed
    @taccommandeur Can you open an issue for this and fill out the fields? That helps us to narrow it down.
    taccommandeur
    @taccommandeur
    I can make an issue for this, but I am probably just doing something wrong so it is most likely not an issue with the package.
    taccommandeur
    @taccommandeur
    I found out that an issue exists json-api-dotnet/JsonApiDotNetCore#922
    taccommandeur
    @taccommandeur
    And it has a workaround that fixed the issue for me :)
    This package is really great so far.
    Bart Koelman
    @bart-degreed
    Thanks
    Björn Harrtell
    @bjornharrtell
    Unless I'm mistaken publicName for a resource is pluralized by default (not sure if that was changed at some point) and since 4.0.0 stable release it does not accept anything else in payloads. In 4.0.0-beta1 it seems it accepted singular name (or possibly didn't even validate at all if it was deducable from relationship).
    1 reply
    Björn Harrtell
    @bjornharrtell
    I'll see if I can get to create a good reproduction. I'm undecided if there is something to actually fix though.
    Bart Koelman
    @bart-degreed
    You've got another release ready for use: JsonApiDotNetCore v4.2! See the release notes at https://github.com/json-api-dotnet/JsonApiDotNetCore/releases/tag/v4.2.0 and https://github.com/json-api-dotnet/JsonApiDotNetCore.MongoDb/releases/tag/v4.2.0-alpha1 for what's new.
    Bart Koelman
    @bart-degreed
    We need some help! Does anyone know Ember.js? Although I'd never used Ember.js before, I was able to update https://github.com/json-api-dotnet/TodoListExample to the latest version. It works, but it produces many linter errors due to old JavaScript syntax. And it has various security vulnerabilities for old depencencies. So it would be great if someone can give it some love and update it to modern standards, possibly add some styling too. PRs welcome!
    Björn Harrtell
    @bjornharrtell
    I'm quite fluent in Ember. I'll check it out. 🙂
    2 replies
    Pranav Singh
    @pranavq212
    I want only to use GET methods & disable all other methods for PUT, DELETE OR POST in all controllers. Is there some configuration that allows this?
    2 replies
    In Other words I want only read-only JSON API, is there any out-of-box way to do this ?
    jrlmasangkay
    @jrlmasangkay

    Hi All, I have an issue with binding a PATCH request body to my model.

    I've done the follow steps as per the docs:

    1. Added all my tables to the DbContext
    2. Called "discovery.AddCurrentAssembly" in ConfigureServes

    But it's still coming up as null when I try to hit the API.
    I'm using EntityFramework btw.

    Would anyone know why the binding is not registering?

    2 replies
    jrlmasangkay
    @jrlmasangkay
    Hi All, another question. Any ideas on what could cause slow data binding for atomic operations? It takes me 40 seconds to bind a request body containing only 1 add request. I can log an issue if required but I just wanted to know first if anyone else has encountered this issue?
    8 replies
    RKennedy9064
    @RKennedy9064
    I've got another quick question if someone has some spare time. What's the proper way to implement a custom route in a JsonApiController? Essentially I want to create a route that I can query to get the current users information after they've logged in with a basic route like api/v1/me, that just returns info for the current user. I know I can override the controller methods like GetAsync, but I don't see an example of adding a custom route to a JsonApiController. Is something like that even possible? Worst case I can just make a normal ApiController and create the /me route there, but was hoping I could just add it to my existing Users controller.
    2 replies
    taccommandeur
    @taccommandeur
    Hi, I have an issue with hydration of a field that does some prosessing when setting:
    public class User : Identifiable<Guid>
    {
        [Key]
        public override Guid Id { get; set; }
    
        [Attr]
        public string Password
        {
            get => "";
            set => FillPassword(value);
        }
    
        [JsonIgnore]
        public string PasswordHash { get; set; }
    
        public void FillPassword(string password)
        {
            PasswordHash = BCryptNet.HashPassword(password);            
        }
    }
    When passing the password attribute in the body, the FillPassword method is called and I see that the PasswordHash is filled. But the value for the password hash is not persisted in the db.
    Is the above something that is not possible with this package?
    taccommandeur
    @taccommandeur
    public override Task OnWritingAsync(User resource, OperationKind operationKind, CancellationToken cancellationToken)
    {
        var test = ""; // If I put a breakpoint on this line I can see that resource.PasswordHash is null
    
        return base.OnWritingAsync(resource, operationKind, cancellationToken);
    }
    I also have a resource definition, with the above method, which is triggered.
    taccommandeur
    @taccommandeur

    Also, when I do this in a dummy controller:

    User user = new() { Password = "somepassword",  Email = "test@test.te" };
    _userRepository.Save(user);

    Then the password hash is persisted in the db

    Bart Koelman
    @bart-degreed
    The User instance from the incoming request body is not the one being saved. See the resource definition docs on when attribute values are copied.
    taccommandeur
    @taccommandeur
    Ok, I will check it out
    taccommandeur
    @taccommandeur
    I found out when the operations feature gets slow
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddDbContext<SampleContext>(
                    optionsBuilder => optionsBuilder
                        .UseMySql("server=127.0.0.1;database=sample;user=root;pwd=root", ServerVersion.Parse("5.7.34-mysql"))
                );
    
                services.AddJsonApi<SampleContext>(options => {
                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                    options.Namespace = "resource-api/v1";
                    options.DefaultPageSize = null;
                    options.IncludeTotalResourceCount = true;
                });
    
                services.AddControllers(); // With this line added, the endpoint /resource-api/v1/operations becomes slow (1+ minutes)
            }
    3 replies
    taccommandeur
    @taccommandeur
    I have another question
    When using the OnWritingAsync method for executing extra logic when a resource is deleted. Only the ID field seems to be filled.
    2 replies
    taccommandeur
    @taccommandeur
    In my case, I have a file resource that has a field FilePath, which points to a file in the file system. So what I want to do is use the OnWritingAsync callback to remove the file from the file system when the resource is removed.
    public override Task OnWritingAsync(File resource, OperationKind operationKind, CancellationToken cancellationToken)
    {
        switch (operationKind)
        {
            case OperationKind.DeleteResource:
                _fileSystem.DeleteAtPath(resource.FilePath); // Only the resource ID seems to be filled on delete.
                                                             // So this breaks, since FilePath is null.
                break;
        }
        return base.OnWritingAsync(resource, operationKind, cancellationToken);
    }
    If I reload the entity from a repository, the entity framework gives errors because then the same entity is being tracked twice.
    dickalexei
    @dickalexei

    Hi,
    I'm trying to update a value in a json via PATCH but facing an error.
    BODY:

    {
      "data": {
        "type": "users",
        "id": "6",
        "attributes": {
          "meta": {
                "location": {
                        "lat": "60.6012", 
                        "lng": "50.5018"
                }
            }
        }
      }
    }

    ERROR:

    Can not convert Object to String. - Request body:

    Is there any particular format to PATCH values in JSON?
    Thanks

    2 replies
    Martin
    @roden23_gitlab

    Hello,
    I have the Json.Api.NetCore setup with no EF integration as I'm going to use a different db/data provider. I would like to use all the filtering/sorting/paging functionality but I'm a little bit struggling with accessing that query string data in my service provider. The code example looks like this:

    public class InstrumentsService : IResourceService<Instrument>
        {
            private readonly IQueryConstraintProvider _queryConstraintProvider;
    
            private IReadOnlyCollection<Instrument> Results = new List<Instrument>
            {
                new Instrument
                {
                    Id = 1,
                    InstrumentCode = "VOD.LN",
                    DisplayName = "Vodafone Plc.",
                    Status = "Test"
                },
                new Instrument
                {
                    Id = 2,
                    InstrumentCode = "ABD.LN",
                    DisplayName = "Aberdeen Plc.",
                    Status = "Test 1"
                },
                new Instrument
                {
                    Id = 3,
                    InstrumentCode = "SL.LN",
                    DisplayName = "Santander Plc.",
                    Status = "Test 99"
                }
            };
    
            public InstrumentsService(IQueryConstraintProvider queryConstraintProvider)
            {
                _queryConstraintProvider = queryConstraintProvider;
            }
    
    
            public Task<IReadOnlyCollection<Instrument>> GetAsync(CancellationToken cancellationToken)
            {
                var constraints = _queryConstraintProvider.GetConstraints();
    
                return Task.FromResult(Results);
            }
        }

    I'm using the IQueryConstraingProvider to get the constraints, but not sure how to parse that so I could get some collection with typed props instead of strings. Is there anything in Json.Api library that could be used for such stuff?

    5 replies
    Bezz242
    @Bezz242

    HI all,

    I'm using json-api-dotnet-core, version 4.2.0 and I'm having a bit of trouble with case sensitivity. In our entity/model, we use an enum with items like BicycleSeat, CarSeat etc. (Pascal casing) From our client, we get bicycleSeat, carSeat etc. (camelCasing), because the frontend is Javascript. I get an InvalidRequestBodyException, internally from Enum.TryParseByName. I'm hoping to fix this with a naming strategy, but I have no clue where to set this. Do I need to include something in app.UseJsonApi, some settings object?

    Much obliged.

    Cheers, Eric

    12 replies
    Bezz242
    @Bezz242

    I tried adding this:

    services.AddJsonApi(options =>
            {
                options.SerializerSettings.ContractResolver = new DefaultContractResolver
                {
                    NamingStrategy = new CamelCaseNamingStrategy()
                };
            });

    but that didn't help. Strangely, when I did this, I got 404 errors on a Post. No exception.

    1 reply
    Bezz242
    @Bezz242
    In OnWritingAsync, I'm doing some checking on what we get from the server. If I want to send a 400 to the client, how do I do that? I assume an exception will turn into a 500. There is the cancellation token. Is that the way? If so, how can I tell the client that it was an error on that side?
    2 replies
    Maurits Moeys
    @maurei
    @/all, since people have been asking about support for swagger I figured I'd make an announcement about this. For a while we have been experimenting in a private repository with an OpenAPI/Swagger integration with JADNC using Swashbuckle. It's not finished, but we have reached the point that we want to start integrating it in the main JADNC repository. See json-api-dotnet/JsonApiDotNetCore#1046 for more information, and keep an eye out on it to track the progress on this feature :)
    rahultandial87
    @rahultandial87

    HI Team,

    I have my model structure with 2 models Employee(EmployeeId, Name, JoiningDate) and EmployeeActivityHistory(EmployeeActivityId, EmployeeId, Designation, Duration ), where there is onetomany relationship present.

    I am trying to filter Employees based on the designation as "intern" in EmployeeActivityHistory. I am using the below URL.

    http://localhost/api/employees?include=employeeActivityHistory&filter[employeeActivityHistory]=equals(Designation,%27Intern%27)

    However, instead of getting all employees with Designation "intern" I am getting first 10 employees in Employee table and the data atrribute set to [] with no match and data tag set to EmployeeActivity in case there is a match.

    How can I get only the employees with designation as "intern".

    7 replies
    Bezz242
    @Bezz242
    Hi all, read something about nested filtering on enums being broken, but is it possible to do simple filtering on enum? If so, what is the syntax?
    10 replies
    Bezz242
    @Bezz242
    Hi all, I have, for a scheduling app, a professional, for instance Nurse, and a TimeSlot in a schedule. Nurse and TimeSlot are many to many, so there is a TimeSlotNurse entity for these relatinships. I want to have unique TimeSlot-Nurse combinations in the TimeSlotNurse entity. Can I enforce this uniqueness in the Post for TimeSlotNurse? TimeSlot and Nurse are {HasOne][Required] in TimeSlotNurse? Many thanks!
    Bezz242
    @Bezz242

    Hi all, I have, for a scheduling app, a professional, for instance Nurse, and a TimeSlot in a schedule. Nurse and TimeSlot are many to many, so there is a TimeSlotNurse entity for these relatinships. I want to have unique TimeSlot-Nurse combinations in the TimeSlotNurse entity. Can I enforce this uniqueness in the Post for TimeSlotNurse? TimeSlot and Nurse are {HasOne][Required] in TimeSlotNurse? Many thanks!

    Exposing Ids in EF and creating an alternative, composite key, looks like the way.

    Bart Koelman
    @bart-degreed
    Hi @Bezz242, I don't think this is the best place to ask general data modeling questions like this. See the docs at https://docs.microsoft.com/en-us/ef/core/modeling/relationships for the basics. I advise using StackOverflow, where you'll probably have more success getting these things sorted out.
    1 reply
    Thomas Barnekow
    @ThomasBarnekow
    Hi all, I'd be interested in using JsonApiDotNetCore in conjunction with Azure Cosmos DB, in particular with the SQL API. This way, Cosmos DB is a document database with an EF Core provider with some limitations (e.g., related to includes and joins), however. Does anybody have experience with this setup? Does it work? Or should I use the extension mechanisms provided by JsonApiDotNetCore to provide more specific support for Cosmos DB (which would obviously mean more work)?
    Jerome Haltom
    @wasabii
    Heya. Are there any proper instructions about not using EF Core, but overriding the minimum amount? I see how I can implement IResourceService.... but can I just override the ResourceRepository instead? If so, how do I register it? How do I setup AddJsonApi() in such a way that it doesn't do EF, but registers the rest properly?
    2 replies
    Jerome Haltom
    @wasabii
    @bart-degreed Thanks for that. I ended up taking a much different approach you might be interested in. I found the existing EF Core support pretty unfortunate.... since your model classes need to he the same as the entity classes. So I begun writing a much more sophisticated repository layer. Instead of being dependent on EF Core, it can be based on top of any IQueryable provider, and supports complex mapping of source -> target data. So you can use a much different structure for your JSON API than your underlying DbContext might be in.
    9 replies
    Bezz242
    @Bezz242
    Hi all, when I override PatchAsync on a controller and I do a patch, I get a 405 Method not allowed with DELETE, GET and HEAD in the response allow header. Anyone know why this is? (BTW overriding because I get an error when I patch to the default controller implementation of Patch (it IS allowed, but I get a 500 error "The instance of entity type 'Role' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached." on removing a simple relation on the resource).
    Bart Koelman
    @bart-degreed
    @Bezz242 If you want others to invest time by helping you, then dumping vague errors in the chat is not going to get you anywhere. From now on, I'm going to ignore such messages from you. If you want help, read the tips at https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/ and create a proper issue with repro steps, which includes the relevant portions of your code.
    Jerome Haltom
    @wasabii
    Anybody done API versioning with JADNC? Having some trouble getting Swagger to pick up on the controllers.
    1 reply