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
}