A day of dumb…

I spent all day trying to figure something out in Entity Framework that shouldn’t have taken an entire day to figure out. It was so dumb, I feel obligated to post it here.

The code below illustrates the problem. The Test method is simply trying to add a new Child record to the database. Notice that the Child class contains a nullable foreign key to the Parent class public int? ParentId { get; set; } . In theory, that meant I could create a new Child object without having to associate it with a Parent object.

Except any time I tried to save the record, I’d get an error indicating, ultimately, that a new Parent record was being created. But why? I wasn’t creating a new parent record….

OR WAS I?!!?!?

Here’s the pseudo code.. See if you can spot the problem that took me waaaaayyyy too long to find.. 

See it?

Here comes the face palm..

Whether I liked it or not, I was always creating a new Parent object and Entity Framework was adding that new object to the ChangeTracker as an added object.

Please tell me I’m not the only one that makes such simple mistakes. :)