Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ASP.NET Core WebApi Return All Values by Attribute

My WebApi has a table for applications with the following class:

namespace Models.Public
{
    [Index(nameof(UUID), nameof(UID), IsUnique = true)]
    public class Application
    {
        public Application()
        {
            this.UUID = new Guid();
        }

        public int ID { get; set; }
        public Guid UUID { get; set; }
        [Required]
        public string UID { get; set; }
        public string Publisher { get; set; }
        public string Name { get; set; }
        public string Version { get; set; }
    }
}

The field UUID and ID are unique, so I was able to generate the required HttpGet command to obtain the results matching for that.

However, I am trying to obtain an IEnumerable object of all the items that match the Publisher field. That is, return all object that have "Google" as their Publisher.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My attempts have not been successful and I am hoping for some advise to fix my code:

// GET: api/Application/<publisher>
[HttpGet("{publisher}")]
public async Task<ActionResult<IEnumerable<Application>>> GetApplication(string publisher)
{
    var application = await _context.Application.ToListAsync(publisher);

    if (application == null)
    {
        return NotFound();
    }

    return await _context.Application.ToListAsync();
}

Publisher is not a unique value, so I’d like to be able to return all items as a JSON object that have whatever Publisher I type in the list. If no matches, error handle with NotFound();.

>Solution :

You will need to filter using .Where, .Contains

// GET: api/Application/<publisher>
[HttpGet("{publisher}")]
public async Task<ActionResult<IEnumerable<ApplicationData>>> GetApplication(string publisher)
{
    var applications = _context.Application.Where(a=>a.Publisher.Contains(publisher)));

   /* You could also use == for exact match
      var applications = _context.Application.Where(a=>a.Publisher == publisher));
   */

    if (applications.Count() == 0)
    {
        return NotFound();
    }

    return await applications.ToListAsync();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading