1

my question is simple, I´m try to do a controller that pass some attributes of a Model

This is the method:

[HttpGet("getAllUserInfo")]
public async Task<ActionResult<object>> GetAll() {
    var test = await _context.Users.ToListAsync(); //here I have the all Info of all users

    //In the return I want pass some attributes of user, creating a new object (ex: The user have a password but I don´t want to show that)
    return Ok(new { test.getType().Name, test.getType().Mail });
    //this above is the part of the code I don´t understand
    }

Is there any alternative to this scenario or what are the possible ideas to make this possible?

Sorry if there are any spelling mistakes in the title and document, but I think the idea where I have difficulty understanding is there

2
  • I doubt a getType() method exists unless you wrote it. Commented May 5, 2022 at 11:06
  • David's answer covers simple enough cases. For more sophisticated ones, you'd probably want to create "DTO" versions of your Entity classes and then maybe use some tool like AutoMapper or Mapster or manual mapping. Commented May 5, 2022 at 11:08

1 Answer 1

2

Are you just trying to project a list of objects into a new list of different objects? You can do that with .Select(). For example:

return Ok(test.Select(t => new { Name = t.Name, Mail = t.Mail }));
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, but with that example, it give be not a error but unfortunately gives me a empty object [] , but let me see if the post method is the problem cuz i m having some problems with the bd
@JoséCarlos: If this produces an empty collection then test was an empty collection. What debugging have you done to indicate otherwise?
the problem has resolve and the example you give me it works, thank you
@David This advice by Carlos works, but according to solid principles this approach is bad. Suppose that you will have other Get by Id method. Here you will return new {....} as well. It breaks principle "Don't repeat yourself" Best approach here is to use the mapping service to convert your dto models (after to ListAsync) to view models. See: docs.automapper.org/en/stable/Getting-started.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.