2013-07-15 15 views
0

제품 시나리오와 관련된 시나리오가 있습니다. 그리고 내 수업은 이렇게 좋아.엔티티 프레임 워크 코드의 Null 외래 키

 

    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 예외 (일부 제품의 브랜드에서 null이 반환 됨)가 발생하지만 GetByID()가 가져 오는 모든 제품에서 예외가 발생합니다.

답변

0

dB에서 값을 가져 오는 중에는 부모 테이블 (브랜드)과 관련된 테이블 (제품)이 포함됩니다.

예 :

VAR 브랜드 = context.Brand.include ("제품");

+0

여전히 GetAll() 메서드에서이 오류가 발생합니다. 리턴 된 데이터에 널 값과 int 값이 있으면 예외를 던집니다. – PolatYerimdar

관련 문제