EF加载相关数据问题 [英] EF loading related data issue
问题描述
我有两个实体:
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>();
}
}
这是控制器的动作.
public ActionResult Index()
{
var genres = db.Genres.ToList();
return View(genres);
}
我在流派和专辑之间有一对多的映射关系(一个专辑只能有一个流派,但是一个流派可以属于多个专辑).当我尝试获取专辑详细信息(包括类型的导航属性)时,它为我提供了预期的数据.但是,当我尝试显示所有流派时,总会给我0作为专辑计数.我怀疑有约束力的问题,但我无法找出问题所在.如果您能帮助您找出问题,将非常高兴.
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.
推荐答案
对于导航属性,您必须使用 ICollection
而不是 IEnumerable
:
You must use ICollection
instead of IEnumerable
for your navigation properties :
public virtual ICollection<Album> Albums { get; set; }
(例如,请参见此 SO答案)
然后,您可以使用 Include
方法通过 Genres
获取相册
:
Then you can use the Include
method to fetch Albums
with Genres
:
db.Genres.Include(genre => genre.Albums)
或
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).
这篇关于EF加载相关数据问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!