我有两个实体:实体框架延迟加载
public class Product
{
[HiddenInput(DisplayValue=false)]
public int ProductID { get; set; }
[Required(ErrorMessage="Please enter a product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Required]
[Range(0.01,double.MaxValue,ErrorMessage="Please enter positive price")]
public decimal Price { get; set; }
public Category Category { get; set; }
[HiddenInput(DisplayValue= false)]
public string ImageFileName { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
和
public class Category
{
[HiddenInput(DisplayValue=false)]
public int CategoryID { get; set; }
[Required(ErrorMessage="Please enter a category name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter a description")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
public ICollection<Product> Products { get; set; }
[HiddenInput(DisplayValue= false)]
public string ImageFileName { get; set; }
[HiddenInput(DisplayValue = false)]
public string ImageMimeType { get; set; }
}
当我试图让产品这样
Product product = repository.Products.FirstOrDefault(p => p.ProductID == id);
类别字段为空。
没有product.Category.Load()和repository.Products.Include(“Category”)...方法。
context.Configuration.LazyLoadingEnabled = false;
不会影响。 上下文是隔壁班
public class EFDbContext:DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
}
的目标我应该如何加载需要的领域?
谢谢
我刚刚尝试以这种方式获取产品对象: Product product =(from repository.Products.Include中的p“Category”)其中p。 ProductID == id select p).SingleOrDefault(); 和类别也被加载。这是可能的解决方案。但有趣的是,为什么类别为空时,我使用第一种方式 – xwrs