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.
[
{
"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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With