【发布时间】:2016-11-16 22:07:39
【问题描述】:
所以我试图将 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.Remove<PluralizingTableNameConvention>();
标签: asp.net-mvc entity-framework asp.net-core