0

I've two entities:

public class Album
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual int GenreId { get; set; }
    public virtual int ArtistId { get; set; }
    public virtual string CoverURL { get; set; }
    public virtual int Cost { get; set; }
    public virtual Artist Artist { get; set; }
    public virtual Genre Genre { get; set; }
}

public class Genre
{
    public int Id { get; set; }       
    public string Name { get; set; }
    public virtual IEnumerable<Album> Albums{get;set;}
    public int AlbumCount { get { return Albums.Count(); } }
    public Genre()
    {
        Albums = new List<Album>();
    }
}

and here is the controller action.

public ActionResult Index()
    {
        var genres = db.Genres.ToList();
        return View(genres);
    }

I've one to many mapping between Genre and Album( A album can have only one genre, but a genre can belong to multiple albums). When i try to fetch Album details(including genre nav. property) it gives me expected data. But when i try to display all genres it always gives me 0 as album count. I suspect a binding issue, but i'm unable to find out where. Would be glad if you can help find out the issue.

Ashish Charan
  • 2,347
  • 4
  • 21
  • 33

2 Answers2

2

You must use ICollection instead of IEnumerable for your navigation properties :

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

(See this SO answer for example)

Then you can use the Include method to fetch Albums with Genres :

db.Genres.Include(genre => genre.Albums)

or

db.Genres.Include("Albums")

EDIT : read this SO answer for more informations about collection types. Basically, ICollection inherits from IEnumerable, and allows you to modify your collection (IEnumerable's main purpose is iteration).

Community
  • 1
  • 1
Réda Mattar
  • 4,361
  • 1
  • 18
  • 19
0

Have you tried this?

public ActionResult Index()
{
    var genres = db.Genres.Include(x => x.Albums).ToList();
    return View(genres);
}
andreasnico
  • 1,478
  • 14
  • 23
  • Yup tried this. But it gives me syntax error. Possibly the EF framework I'm using doesn't support this. It expects a "string path" as argument. – Ashish Charan Dec 30 '13 at 11:49
  • Have you tried with a string? Like this: var genres = db.Genres.Include("Albums").ToList(); – andreasnico Dec 30 '13 at 11:51
  • A specified Include path is not valid. The EntityType 'MvcMusicStore.DAL.Genre' does not declare a navigation property with the name 'Albums'. This error comes. – Ashish Charan Dec 30 '13 at 11:54
  • Have you configured your modelbuilder correct? Something like this: modelBuilder.Entity() .HasMany(x => x.Albums) Read more here: http://msdn.microsoft.com/en-us/data/jj591620.aspx – andreasnico Dec 30 '13 at 12:00
  • No I've not configured. Is it necessary? – Ashish Charan Dec 30 '13 at 12:02