Search code examples
entity-frameworkentity-framework-4code-firstef4-code-only

EF4 CodeFirst CTP4 - Insert with existing association


If I have an entity that has an association (e.g. Book.Publisher), how do I save a new Book and associate it with an existing Publisher?

BTW I don't want to expose FK associations (i.e. PublisherId) in my model.

I had been using something like this:

var book = new Book { Title="whatever", Publisher = new Publisher { Id = 42 } };
context.Books.Add(book);

But this just tries to add a new publisher.

I saw this question which suggested using ObjectStateManager.ChangeObjectState but I get an error if I try this - The ObjectStateManager does not contain an ObjectStateEntry with a reference to an object of type 'Blah.Publisher'.


Solution

  • var pub = new Publisher { Id = 42 };
    context.Publishers.Attach(pub);
    var book = new Book { Title="whatever", Publisher = pub };
    context.Books.Add(book);