Entity Framework 4: POCO and Foreign Keys in Beta 2 – updates not persisted

Whilst preparing some demos for a customer session on Entity Framework 4 recently, I was putting together a demo to show how Entity Framework can work with POCO types. The intention was to show code that worked with the automatically generated types and then switch out the types for a POCO implementation and show that the same code still ran, complete with change tracking and lazy loading.

Unfortunately, as I put the code together I was unable to get it working so I had to modify the demo. I’ve since discovered that I had encountered a known issue in Beta 2 that has been fixed in later builds!

I had code along the lines of the following:

 using (var context = new NorthwindEntities())
{
    var customer = context.Customers.Single(c => c.CustomerID == "AROUT");
    var product = context.Products.Single(p => p.ProductID == 1);
    var order = new Order()
    {
        OrderDate = DateTime.Today,
        Customer = customer,
    };

    Order_Detail orderDetail = new Order_Detail
    {
        Product = product,
        Quantity = 1,
    };
    order.Order_Details.Add(
        orderDetail
        );

    context.Orders.AddObject(order);
    context.SaveChanges();
}

With this code, the newly created order wasn’t being saved to the database. It turns out that there are a couple of workarounds:

  • use customer.Orders.Add(order) instead of order.Customer = customer (and similiarly for the product reference on the order details)
  • set order.Customer = customer after adding the order to the context (i.e. after the AddObject call)

I opted for the latter workaround as it seemed slightly simpler to me. Sure enough, I was up and running again in a jiffy.

 using (var context = new NorthwindEntities())
{
    var customer = context.Customers.Single(c => c.CustomerID == "AROUT");
    var product = context.Products.Single(p => p.ProductID == 1);
    var order = new Order()
    {
        OrderDate = DateTime.Today,
        //Customer = customer,
    };

    Order_Detail orderDetail = new Order_Detail
    {
        //Product = product,
        Quantity = 1,
    };
    order.Order_Details.Add(
        orderDetail
        );

    context.Orders.AddObject(order);
    orderDetail.Product = product; // BUG in Beta 2 - set this after adding the order to the context
    order.Customer = customer; // BUG in Beta 2 - set this after adding the order to the context
    context.SaveChanges();
}

Looking forward to the next release!