Home > Enterprise >  How to put values in a list type field
How to put values in a list type field

Time:04-15

I have 2 classes and VMs. I made a method that displays typegenres, and a list of genres that are related to them, but now I need a list of TypeGenreNamesVM. I don't understand how to pass in GenreNames a list of values Name and NameUrl. I need to make a method that displays data in a similar structure:

[
  {
   "name": "qwerty",
   "nameEng": "qwertyEng",
   "GenresNames": [
      {
       "name": "genre1",
       "nameEng": "genreEng1"
      },
      {
       "name": "genre2",
       "nameEng": "genreEng2"
      }
   ]
  }
]

Here is I have 2 classes and VMs that I using

 public class Genre
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string NameForUrl { get; set; }
        public string Description { get; set; }
        public int Fk_TypeGenreId { get; set; }
        [ForeignKey("Fk_TypeGenreId")]
        public TypeGenre TypeGenre { get; set; }
        public List<Book_Genre> Book_Genre { get; set; }
    }

    public class TypeGenre
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string NameForUrl { get; set; }
        public string Description { get; set; }
        public List<Genre> Genre { get; set; }
    }
  
    public class TypeGenreTestVM
    {
        public string Name { get; set; }
        public string NameEng { get; set; }
        public List<TypeGenreNamesVM> GenreNames { get; set; }
    }

    public class TypeGenreNamesVM
    {
        public string Name { get; set; }
        public string NameForUrl { get; set; }

    }
    public async Task<IEnumerable<TypeGenreTestVM>> GetTypesAndGenresEng()
    {
        var result = await _context.TypeGenre.Select(genres => new TypeGenreTestVM()
        {
            Name = genres.Name,
            NameEng = genres.NameForUrl,
            GenreNames = 

        }).ToListAsync();

        return result;
    }

CodePudding user response:

Almost the same as the first Select

public async Task<IEnumerable<TypeGenreTestVM>> GetTypesAndGenresEng()
{
    var result = await _context.TypeGenre.Select(genres => new TypeGenreTestVM()
    {
        Name = genres.Name,
        NameEng = genres.NameForUrl,
        GenreNames = genres.Genre.Select(g => new TypeGenreNamesVM
        {
            Name = g.Name,
            NameEng = g.NameForUrl 
        })
        .ToList()
    }).ToListAsync();

    return result;
}
  • Related