I’m using EF4.1 Code First. I can’t get a very simple insert to save the related entity ID. The generated SQL always inserts NULL for any related entities. Example code is below. Can anyone see what I’m doing wrong here? It does properly insert non-entity properties, such as strings. Also I have similar code in a DB initializer class to seed test data and it seems to work fine.
using (var ctx = new DataContext())
{
ctx.Users.Attach(existingUser);
// create item and add to context
var newItem = new MyItem();
ctx.MyItems.Add(newItem);
// set related entity
newItem.CreatedBy = existingUser;
ctx.SaveChanges();
}
Your code should work with default configuration of your
DbContext. One possible explanation that it does not work is that you have automatic change detection disabled, for instance if you have in your context’s constructor something like:In this case EF would not detect the change of the navigation property
newItem.CreatedByafter you have added the new item to the context. (SaveChangeswould detect this last change if change detection isn’t disabled.)You can change your code so that setting the navigation property happens before you add the new item to the context:
This should work with and without automatic change detection.