Reputation: 11806
I have a code first model:
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; }
}
}
In the controller, I am trying to load all the Creators
that are associated with a particular issue:
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;
}
But this won't compile... Why won't this compile?
Specifically; the line that says:
foreach (var item in issue.Creators)
won't compile because of an error that says:
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
What's up with that? :-)
I went back and doublechecked my controller (you can just scroll up) and, yep; there it is! Creators
is a property of Issues
. So what gives? Maybe it has something to do with lazy loading?
Upvotes: 1
Views: 179
Reputation: 8067
Try using Single()
instead of Where()
in db.Issues.Where(x => x.IssueId == 8)
var issue = db.Issues.Single(x => x.IssueId == 8);
Upvotes: 2
Reputation: 126577
Your query is wrong. You want:
var issue = db.Issues.Where(x => x.IssueId == 8).Single();
You are expecting a single issue, not a list of one issue.
Upvotes: 1