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

Community
  • 1
  • 1
Paul Hiles
  • 9,558
  • 7
  • 51
  • 76
  • Can you provide more info about your implementation? I have no problem to use ObjectStateManager when using AddObject on ObjectSet. – Ladislav Mrnka Sep 03 '10 at 18:46

1 Answers1

3
var pub = new Publisher { Id = 42 };
context.Publishers.Attach(pub);
var book = new Book { Title="whatever", Publisher = pub };
context.Books.Add(book);
Craig Stuntz
  • 125,891
  • 12
  • 252
  • 273
  • 1
    Should be context.Publishers.Attach(pub) but thanks a million. The ObjectStateManager approach seemed a bit overboard. – Paul Hiles Sep 03 '10 at 23:31
  • 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! – Jason Kleban Oct 29 '10 at 06:20
  • 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. – Jason Kleban Oct 29 '10 at 14:53
  • @uosɐſ: It [*is* in the documentation.](http://msdn.microsoft.com/en-us/library/bb896271.aspx) – Craig Stuntz Oct 29 '10 at 15:05