views:

163

answers:

1

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'.

+1  A: 
var pub = new Publisher { Id = 42 };
context.Publishers.Attach(pub);
var book = new Book { Title="whatever", Publisher = pub };
context.Books.Add(book);
Craig Stuntz
Should be context.Publishers.Attach(pub) but thanks a million. The ObjectStateManager approach seemed a bit overboard.
zaph0d
But doesn't that require another trip to the database to load this data in? I don't care what the data is, I just want to reference it!
uosɐſ
@uosɐſ: No. Have you tried it?
Craig Stuntz
Well, this is the kind of thing I'd rather find documentation on. Testing to prove conclusively that additional database trips aren't involved would be complicated. That's why I'm asking.
uosɐſ
@uosɐſ: It [*is* in the documentation.](http://msdn.microsoft.com/en-us/library/bb896271.aspx)
Craig Stuntz