This is my first code-first project and have never had an issue doing this in db-first, that I can remember. So, I'm either missing something obvious or there's a rule I missed somewhere. I do not want to use lazy loading, and have to think that it's not required to do this, given the many examples using eager loading.
Very simple. Parent record is Listing, child records are Bid entities:
public class Listing {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ListingID { get; set; }
[Required]
[StringLength(140)]
public string Title { get; set; }
//...etc.
public List<Bid> Bids { get; set; }
public Listing() {
Bids = new List<Bid>();
}
}
public class Bid {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int BidID { get; set; }
[Required]
public decimal Amount { get; set; }
//...etc.
public int ListingID { get; set; }
[ForeignKey("ListingID")]
public Listing Listing { get; set; }
public Bid() {
Listing = new Listing();
}
}
I'm using Include to pull the child records:
using (var db = new MyDbContext()) {
var listing = db.Listings
.Where(x => x.Active == true && x.UserID == "abc123")
.Include(x => x.Bids)
.FirstOrDefault();
}
Child collection exists but is always empty (Count = 0) - it's not pulling the records. They're definitely in the tables. I can manually query this and get those bid records, no problem. Basically, I need a listing and all of its bids, similar to this:
select l.*, b.*
from Listing l
inner join Bid b on l.ListingID = b.ListingID
where l.Active = 1
and l.UserID = 'abc123'
What's missing? This article says I'm doing it right: