Reputation: 5175
I have read some here: http://www.asp.net/mvc/tutorials/mvc-music-store-part-4 and set some stuck
namespace MvcMusicStore.Models
{
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
}
namespace MvcMusicStore.Models
{
public class Album
{
public int AlbumId { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public string AlbumArtUrl { get; set; }
public Genre Genre { get; set; }
public Artist Artist { get; set; }
}
}
namespace MvcMusicStore.Models
{
public partial class Genre
{
public int GenreId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public List<Album> Albums { get; set; }
}
}
In the Album Class, why they have:
public Genre Genre { get; set; }
public Artist Artist { get; set; }
And in the Genre class, why they have:
public List<Album> Albums { get; set; }
Can you explan for me why we should have these fields?
Upvotes: 1
Views: 2728
Reputation: 24236
The properties provide access to the linked objects on each object, they allow us to do things in code like -
var GenreName = album.Genre.Name
var ArtistName = album.Artist.Name
Similarly you could iterate through the Albums linked to a Genre using the public List<Album> Albums
property. The Entity framework will populate the necessary linked properties on objects with the relevant data from the database. The linked property data can be loaded immediately or lazily depending on how the entity framework code is called.
As an example here's some code that pulls out albums that are linked to a particular genre, notice how the Include
function is called, the function ensures that Album
data is pulled from the database at the same time the Genre
information is pulled -
public ActionResult Browse(string genre)
{
// Retrieve Genre and its Associated Albums from database
var genreModel = storeDB.Genres.Include("Albums")
.Single(g => g.Name == genre);
return View(genreModel);
}
Upvotes: 2
Reputation: 1824
Totally logical. each album has an you listen to has a genre and an artist. so he created a custom object of both genre and artist example this:
public class Artist
{
public int ArtistId { get; set; }
public string Name { get; set; }
}
this is done to map it to a table in a database most probably that has an ID and a name of the artist. similarly to genre.
as for the List each genre like Rock has multiple albums inside it thats why he decared a list of the object of album inside the object genre that he is using.. he will add list of objects albums to genre and then maybe save them in the database as a one to many relationship. well he could have saved a list of ID of the AlbumID that would be better, but im not sure of the full logic maybe is is using the full object elsewhere
Upvotes: 1