我在通过延迟加载加载ICollection
对象时遇到问题。
public class Product
{
[Key]
public int Id { get; set; }
public string OrderNum { get; set; }
public DateTime DateOfPurchased { get; set; }
public int CustomerId { get; set; }
public virtual ICollection<OrderedItem> OrderedItems { get; set; }
public virtual Customer Customer { get; set; }
}
public class OrderedItem
{
[Key]
public int Id { get; set; }
public int ProductId { get; set; }
public int? Quantity { get; set; }
public int? ItemId { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? Profit { get; set; }
public virtual Item Item { get; set; }
public virtual Product Product { get; set; }
}
每当我将数据加载到Product
时,除ICollection
属性外,可以加载所有属性。我犯了什么错误吗?
答案 0 :(得分:2)
嗨,我在我的本地电脑上尝试了这个并且它有效。下面是Model类和dbContext类。我删除了一些属性以使其简单。就模型创建而言,我添加了一行。
EF课程
public class Product
{
[Key]
public int Id { get; set; }
public string OrderNum { get; set; }
public DateTime DateOfPurchased { get; set; }
public int CustomerId { get; set; }
public virtual ICollection<OrderedItem> OrderedItems { get; set; }
}
public class OrderedItem
{
[Key]
public int Id { get; set; }
public int ProductId { get; set; }
public int? Quantity { get; set; }
public int? ItemId { get; set; }
public decimal? TotalPrice { get; set; }
public decimal? Profit { get; set; }
public virtual Product Product { get; set; }
}
我的DBCOntext课程:
public class SampleDbContext : DbContext
{
public SampleDbContext()
: base("name=SampleDBConnection")
{
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = true;
}
public DbSet<Product> Products { get; set; }
public DbSet<OrderedItem> OrderedItems { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().HasMany(c => c.OrderedItems);
}
}