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