Mr_LinDowsMac
Mr_LinDowsMac

Reputation: 2702

Merge Json results into one

I have the following code in a controller, as you can see it returns an object serialized to Json.

...
     [HttpGet("{id}")]
            public IActionResult Get(string id)
            {
                ClientsRepository ClientsRepo = new ClientsRepository(connectionString);
                return Json(ClientsRepo.GetClientCreditSummary(id));
            }
...

The method where it gets the data is in a ClientsRepo.GetClientCreditSummary, and I would like to merge it with another one called ClientsRepo.GetClient, and return it as a Json result in this same controller action.

How can I do that?

Upvotes: 0

Views: 213

Answers (2)

Mattias Åslund
Mattias Åslund

Reputation: 3907

It's not very good form to take two object like that and mush together into one.

Consider instead making a new object that holds the other two as properties:

[HttpGet("{id}")] 
public IActionResult Get(string id
{
    var repo = new ClientsRepository(connectionString);
    var creditSummary = repo.GetClientCreditSummary(id);

    var client = repo.GetClientById(id);

    var result = new
    {
        Client = client,
        CreditSummary = creditSummary
    };

    return Json(result); 
}

Upvotes: 0

rashleighp
rashleighp

Reputation: 1226

You can use an anonymous type:

return Json(new { ClientCreditSummary = ClientsRepo.GetClientCreditSummary(id), Client = ClientsRepo.GetClient(id) });

For more on anonymous types http://www.c-sharpcorner.com/UploadFile/ff2f08/anonymous-types-in-C-Sharp/

If you're instead wanting to merge the fields of the two entities into one entity, I think the best way would be to manually map each field into the new entity.

Upvotes: 1

Related Questions