所以我想涉及2個表給對方。我有一個產品表和一個圖像表。我在產品對象中有一個圖像集合,在圖像對象/表中有一個產品ID,但是當它獲取產品對象時,圖像集合是空的。實體框架沒有返回相關對象
現在有趣的是,在調試時,如果在產品對象從其中獲取信息之前檢查上下文元素,它會將圖像加載到上下文元素中,然後將其分配給產品。所以它只在我手動檢查上下文元素時才起作用,然後它搜索圖像。
產品
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; }
}
圖片
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);
}
}
次數據訪問
public Product GetById(string id)
{
Product product = _context.Products.FirstOrDefault(p => p.FriendlyUrl == id);
return product;
}
'_context.Products.Include(X => x.Images).FirstOrDefault(...' –
嘗試使用'modelBuilder.Conventions。刪除();' –
Perdido