c# - Null Foreign Key in Entity Framework code first -


i have classic scenario product-brand relation. , classes this.

      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; }         }     }  

and mapping this.

      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);                  }     }  

i have 2 method, getall(), getbyid() row on product table has null value.

when im try run getall method throwing null exception (some product's brand return null), product getting getbyid() dosent throwing exception?

while getting values db include associated table(products) along parent table(brands).

example :

var brands=context.brand.include("products");


Comments