Note that there are some explanatory texts on larger screens.

plurals
  1. POEntity Framework 5 codefirst / Required and optional foreign key relations are null
    text
    copied!<p>I'm tring to create a DbContext with my entites on entityframework5 codefirst way. I've brands, categories and products. </p> <p>But when I try to get a <code>Product</code> it's <code>Brand</code> and <code>Category</code> fields are null. <code>Category</code> is optional but <code>Brand</code> is not. So at least the Brand field has to be setted. I tried the code below. Is there any thing that I miss?</p> <pre><code> public DbSet&lt;Brand&gt; Brands { get; set; } public DbSet&lt;Product&gt; Products { get; set; } public DbSet&lt;Category&gt; Categories { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity&lt;Brand&gt;() .HasMany(b =&gt; b.Products) .WithRequired(p =&gt; p.Brand) .HasForeignKey(p =&gt; p.BrandId); modelBuilder.Entity&lt;Category&gt;() .HasMany(c =&gt; c.Products) .WithOptional(p =&gt; p.Category) .HasForeignKey(p =&gt; p.CategoryId); } </code></pre> <p>And on MVC controller side:</p> <pre><code> using (var db = new InonovaContext()) { var product = db.Products.Single(p =&gt; 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 } </code></pre> <p>Product class is like below</p> <pre><code>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; } } </code></pre> <p>Brand class is like below:</p> <pre><code>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&lt;Product&gt; Products { get; set; } } </code></pre> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload