So I am trying to relate 2 tables to each other. I have a product table and an image table. I have a collection of images in the product object and a product ID in the image object/table but when it gets the product object, the image collection is empty.
Now interestingly enough, when debugging, if I inspect the context element before the product object pulls the info from it, it loads the images in the context element, and THEN it will be assigned to the product. So it works ONLY when I manually inspect the context element and it searches for the images then.
Product
public class Product
{
public int Id { get; set; }
public string FriendlyUrl { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public double? Price { get; set; }
public double? Weight { get; set; }
public int? Stock { get; set; }
public virtual ICollection<Image> Images { get; set; }
}
Image
public class Image
{
public int Id { get; set; }
public int ProductId { get; set; }
public string FileName { get; set; }
}
DBContext
public class TheContext : DbContext
{
public TheContext(DbContextOptions<TheContext> options) : base(options)
{
}
public DbSet<Product> Products { get; set; }
public DbSet<Image> Images { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasMany<Image>(s => s.Images);
}
}
Data Access
public Product GetById(string id)
{
Product product = _context.Products.FirstOrDefault(p => p.FriendlyUrl == id);
return product;
}