Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get data in string array or JSON format using linq to entities?

I have an ASP.Net MVC5 site and using EF 6.0

One to Many relationship

Here are my models

public class Singer
{
    [Key]
    public int SingerID { get; set; }

    public string SingerName { get; set; }

    public virtual List<Album> Albums { get; set; }
}

public class Album
{
    [Key]
    public int AlbumID { get; set; }

    public string AlbumName { get; set; }

    public string AlbumDate { get; set; }

    [ForeignKey("Singer")]
    public int SingerID { get; set; }

    public virtual Singer Singer { get; set; }
}

Now my Linq is as below

public IEnumerable<T> GetAlbums()
{
    using (dbContext db = new dbContext())
    {
        IQueryable<T> query = (from c in db.Albums
                               group c.AlbumId by c.SingerId into albums
                               select new AlbumMapper()
                               {
                                   AlbumID = albums.Key,
                                   Total = albums.Count()
                               })
        }
}

In the current scenario I get all the albums grouped by albumId and the count of the albums.

But my need is to form JSON string as below

[
   {
      "SingerID":1,
      "Albums":[
         {
            "AlbumName":"This is Album 1",
            "AlbumDate":"Dec 30,2015"
         },
         {
            "AlbumName":"This is Album 2",
            "AlbumDate":"Dec 30 2015"
         }
      ]
   },
   {
      "SingerID":2,
      "Albums":[
         {
            "AlbumName":"This is Album 1",
            "AlbumDate":"Dec 30,2015"
         },
         {
            "AlbumName":"This is Album 2",
            "AlbumDate":"Dec 30 2015"
         }
      ]
   }
]

Adding Mapper Classes

public class AlbumDetails
{
   public DateTIme AlbumDate

   public string AlbumName

}

public class AlbumMapper
{
    public int AlbumID

    public IEnumerable<AlbumDetails> Albums  
}
like image 867
Kgn-web Avatar asked Nov 16 '25 08:11

Kgn-web


1 Answers

Just put all the Singers into a list and serialize it using Json.NET (http://www.newtonsoft.com/json)

If you want to leave out SingerName be sure to add a [JsonIgnore] data attribute to the property

like image 171
Robert Avatar answered Nov 18 '25 23:11

Robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!