One-To-Many relationship in Entity Framework: Why foreign key value is null?

asp.net-core c# entity-framework-core linq

Question

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.

1
1
2/4/2020 8:42:20 PM

Accepted Answer

You need to specify EF to include child.

var company = await _context.Company.Where(p => p.companyName == "BestCompany").Include(p=> p.PhotoCollection).FirstOrDefaultAsync();
2
2/4/2020 8:24:35 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow