我有一个经典的场景产品 - 品牌关系。而我的课程就是这样。
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()获取的所有产品都会抛出任何异常?
答案 0 :(得分:0)
从dB获取值包括关联表(产品)以及父表(品牌)。
示例:
var brands=context.Brand.include("Products");