Entity Framework 5 codefirst / Mandatory and optional foreign key relationships are null

I am trying to create a DbContext with my entites on entityframework5 codefirst. I have brands, categories and products.

But when I try to get Product , the Brand and Category fields are null. Category is optional, but Brand is not. Therefore, you must at least set the Brand field. I tried the code below. Is there something I missed?

  public DbSet<Brand> Brands { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Brand>() .HasMany(b => b.Products) .WithRequired(p => p.Brand) .HasForeignKey(p => p.BrandId); modelBuilder.Entity<Category>() .HasMany(c => c.Products) .WithOptional(p => p.Category) .HasForeignKey(p => p.CategoryId); } 

And on the MVC side:

  using (var db = new InonovaContext()) { var product = db.Products.Single(p => p.Id == id); model.Description = product.Description; model.ImageUrl = product.ImageUrl; model.Name = product.Name; model.BreadCrumb = product.Brand.Name + " / " + product.Category == null ? "" : (product.Category.Name + " / ") + product.Name; // Here Brand and Category are null } 

Product class similar to below

 public class Product { public int Id { get; set; } public int BrandId { get; set; } public virtual Brand Brand { get; set; } public string Name { get; set; } public int? CategoryId { get; set; } public virtual Category Category { get; set; } public string ImageUrl { get; set; } public string Description { get; set; } } 

The brand class is as follows:

 public class Brand { public int Id { get; set; } public string Name { get; set; } public string ThumbLogoImageUrl { get; set; } public string Description { get; set; } public ICollection<Product> Products { get; set; } } 

Thanks.

+6
source share
1 answer

If you have not declared the Brand and Category as virtual, lazyloading the Brand and Category properties will not work.

 public class Product { public int Id { get; set; } public string Name { get; set; } public virtual Brand Brand { get; set; } public int BrandId { get; set; } public virtual Category Category { get; set; } public int? CategoryId { get; set; } } 

See this one for more information on lazy and impatient downloads.

+6
source

Source: https://habr.com/ru/post/954353/


All Articles