我有一个经典的场景产品 - 品牌关系 . 而我的课程就像这样 .
public class Products
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
public string PreDescription { get; set; }
public int? BrandID { get; set; }
//private Brands brand;
public virtual Brands Brand
{
get; //{ if (this.Brand == null) Brand = new Brands(); return Brand; }
set; //{ Brand = value; }
}
}
public class Brands
{
public int BrandID { get; set; }
public string BrandName { get; set; }
private List products;
public virtual List Products
{
get{ if (this.products == null) products = new List(); return products; }
set{ products = value; }
}
}
像这样映射 .
public class ProductsMap : EntityTypeConfiguration{
public ProductsMap()
{
ToTable("Products");
HasKey(p => p.ProductID).Property(p => p.ProductID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasOptional(p => p.Brand).WithMany(b => b.Products);
}
}
public class BrandsMap : EntityTypeConfiguration
{
public BrandsMap()
{
ToTable("Brands");
HasKey(b => b.BrandID).Property(b => b.BrandID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
我有两个方法,GetAll(),GetByID()Product表上的某些行具有Null值 .
当我尝试运行GetAll方法时,它抛出Null Exception(Some Product的品牌返回null),但所有产品都是通过GetByID()获取任何异常?
1 回答
从dB获取值包括关联表(产品)以及父表(品牌) .
例: