views:

213

answers:

1

Using Microsoft Visual C# 2010 Express, Entity Framework Feature CTP4.

I tried EF4 with code first with something small based on Scott Gu's blog. But it seems that collections are not initialized when retrieving an entity. I get a null reference exception when adding a product to a category. In all the examples I've seen, the collection are never explicitly initialized. What am I missing?

Here's my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var _db = new Northwind();

            var c = new Category { CategoryName = "Testcat" };
            _db.Categories.Add(c);
            _db.SaveChanges();

            var c2 = _db.Categories.SingleOrDefault(i => i.CategoryId==c.CategoryId);
            var pr = new Product { ProductName = "testprod" };

            c2.Products.Add(pr);    //  <---  Null reference for Products

            _db.SaveChanges();

            Console.WriteLine("Done...");

            Console.ReadKey();
        }
    }

    public class Product
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public virtual Category Category { get; set; }
    }

    public class Category
    {
        public int CategoryId { get; set; }
        public string CategoryName { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }

    public class Northwind : DbContext
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
    }

}
A: 

as the comment by Yury Tarabanko says, the category that is returned is null since you don't have a category id for c since it hasn't been assigned.

var c2 = _db.Categories.SingleOrDefault(i => i.CategoryName == c.CategoryName);
var pr = new Product { ProductName = "testprod" };

c2.Products.Add(pr); 

will work since you assigned c.CategoryName with the value of "Testcat"

Joakim
See my comment for Yuri, after SaveChanges() the Id is auto-generated.
John Landheer