开发者

EF Code First CTP5 Null child Object handling

开发者 https://www.devze.com 2023-02-21 22:49 出处:网络
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.

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开发者_如何学C can setup my model to handle null Category?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号