简体   繁体   中英

EF loading related data issue

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.

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).

Have you tried this?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM