2013-07-15 71 views
0

我有一個典型的情景產品品牌關係。和我的班級一樣。空實體框架中的外鍵代碼優先

 

    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() 在產品表中的某些行有Null值。

當我嘗試運行GetAll方法它拋出空例外(某些產品的品牌返回null),但所有GetByID()dosent獲得產品拋出任何異常?

回答

0

雖然從dB獲取值包括關聯表(產品)以及父表(品牌)。

實施例:

變種品牌= context.Brand.include( 「產品」);

+0

仍然在GetAll()方法得到這個錯誤。如果返回的數據中有空值以及int值,則拋出異常。 – PolatYerimdar