Search code examples
entity-frameworkef-code-firstentity-framework-ctp5

EF Code First CTP5 Null child Object handling


I have a Product object with a related Category within it.

I have the relationship between product and Category as a One to Many. But the Category can also be null.

Trouble is I cannot seem to handle null Category object.

I tried the following in my Product class:

private Category _category;

public virtual Category Category
{
   get { return _category ?? (_category = new Category()); }

   set { _category = value; }
}

And on my Database Context OnModelCreating method:

 modelBuilder.Entity<Product>()
                .HasRequired(p => p.Category)
                .WithMany(c => c.Products)
                .HasForeignKey(p => p.CategoryId);

Unfortunately on accessing the Product.Category in my design layer it always returns the New Category instance, rather than try to pull the Category by the Product.CategoryId (which does have a value).

How can I can setup my model to handle null Category?


Solution

  • If the Category is optional (it is because it can be null) you must use:

    modelBuilder.Entity() .HasOptional(p => p.Category) .WithMany(c => c.Products) .HasForeignKey(p => p.CategoryId);

    And define your product as:

    public class Product
    {
        ...
        public int? CategoryId { get; set; }
        public virtual Category { get; set; }
    }