EF Core DbSet's "Select" Extension still show other columns

I'm starting to learn ASP and EF Core and currently working on a Web Service.

I already have the following:

  1. Menu Model that has 3 variables/columns
  2. DBContext containing DbSet<'Menu'>
  3. MenuController that has HTTPGet Method

Inside the HTTPGet Method is:

    [HttpGet]
    public List<Menu> Get()
    {
       return db.Menus.Select(p => new Menu
        {
            m_menu = p.m_menu
        }).Distinct().ToList();
    }

My goal is to select only 1 column instead of 3 columns and distinct it. So I use the .Select extension for me to show only 1 specific column which is m_menu.

As I call MenuController, the HTTPGet still response or show all the columns instead of only 1 column(m_menu). The sample result JSON shows other columns with null value and only m_menu has a value.

I read some related problems and suggested to Serialize the JSON but still not help me with this.

Upvotes: 3

Views: 194

Answers (1)

Backs
Backs

Reputation: 24903

Becase your metod returns List<Menu> and Menu has 3 properties: m_id, m_menu and s_menu. If you want to return only one column, you cand return List<string>:

[HttpGet]
public List<string> Get()
{
   return db.Menus.Select(p => p.m_menu ).Distinct().ToList();
}

Upvotes: 4

Related Questions