为什么我的实体框架POCO没有正确加载相关实体?

时间:2011-06-09 16:35:25

标签: entity-framework lazy-loading entity-framework-4.1 entity-relationship

我有一个代码第一个模型:

namespace InternetComicsDatabase.Models
{
    public class Issue
    {
        [Key]
        public int      IssueId     { get; set; }
        public int      Number      { get; set; }
        public string   Title       { get; set; }
        public DateTime Date        { get; set; }

        public virtual ICollection<Creator> Creators { get; set; }
    }

    public class Creator
    {
        [Key]
        public int      CreatorId   { get; set; }
        public string   FirstName   { get; set; }
        public string   MiddleName  { get; set; }
        public string   LastName    { get; set; }

        public virtual ICollection<Issue> Issues { get; set; }
    }

    public class Icbd : DbContext
    {
        public DbSet<Issue> Issues { get; set; }
        public DbSet<Creator> Creators { get; set; }
    }
}

在控制器中,我正在尝试加载与特定问题相关联的所有Creators

    public string CreatorTest()
    {
        string output = "";
        var issue = db.Issues.Where(x => x.IssueId == 8);
        foreach (var item in issue.Creators)
            output += item.FirstName;
        return output;
    }

但这不会编译......为什么不编译?

具体而言;这条线说:

        foreach (var item in issue.Creators)

将无法编译,因为出现错误:

Error   1   'System.Linq.IQueryable<InternetComicsDatabase.Models.Issue>' does not contain a definition for 'Creators' and no extension method 'Creators' accepting a first argument of type 'System.Linq.IQueryable<InternetComicsDatabase.Models.Issue>' could be found (are you missing a using directive or an assembly reference?) C:\Users\dropstuff\asp.net mvc\InternetComicsDatabase\InternetComicsDatabase\Controllers\HomeController.cs  19  31  InternetComicsDatabase

这是怎么回事? : - )

我回去并重新检查我的控制器(你可以向上滚动),是的,是的;它就是! Creators Issues的属性。什么给出了什么?也许它与延迟加载有关?

2 个答案:

答案 0 :(得分:2)

尝试在Single()

中使用Where()代替db.Issues.Where(x => x.IssueId == 8)
var issue = db.Issues.Single(x => x.IssueId == 8);

答案 1 :(得分:1)

您的查询错误。你想要:

var issue = db.Issues.Where(x => x.IssueId == 8).Single();

您期待一个问题,而不是一个问题的列表。