Let's assume each company has some photos (one-to-many relationship).
public class Company
{
[Key]
public int companyID { get; set; }
public string name { get; set; }
// FOREIGN KEY One-To-Many relationship
public ICollection<Photo> PhotoCollection { get; set; }
}
public class Photo
{
[Key]
public int photoID { get; set; }
public string path { get; set; }
}
My database has some records and seems to be correct.
Company table:
CompanyID | Name
----------+---------------------
1 | BestCompany
Photo table:
PhotoID | Path | CompanyID (foreign key)
--------+------------+------------------------
1 | photo1 | 1
2 | photo2 | 1
Getting company to a variable works fine, I can get to it's normal columns (like companyID):
var company = await _context.Company
.Where(p => p.companyName == "BestCompany")
.FirstOrDefaultAsync();
Unfortunately, photos
variable is null:
List<Photo>photos = company.PhotoCollection;
Why is it null? What am I doing wrong?
I use ASP.NET Core 3 and Entity Framework Core 3.1.1.
You need to specify EF to include child.
var company = await _context.Company.Where(p => p.companyName == "BestCompany").Include(p=> p.PhotoCollection).FirstOrDefaultAsync();