I believe that there are several ways to do this. You can indicate that the course object does not change, but is not added in the following lines:
ctx.Entry(course).State = EntityState.Unchanged;
Or instruct your context that you are working with an existing entity:
ctx.Courses.Attach(course);
More details here: http://msdn.microsoft.com/en-us/data/jj592676.aspx
EDIT
There are several test samples in my solution, I checked that they work as expected. In all cases, we have a publisher record in the database with ID = 2 and Name = "Addison Wesley" (not relevant to this example, but only for good measure).
Approach 1 - Setting the state of an entity
using (var context = new Context()) { var book = new Book(); book.Name = "Service Design Patterns"; book.Publisher = new Publisher() {Id = 2 };
Approach 2 - Using the Attach Method
using (var context = new Context()) { var book = new Book(); book.Name = "Service Design Patterns"; book.Publisher = new Publisher() { Id = 2 };
Approach 3 - Setting a Foreign Key Value
using (var context = new Context()) { var book = new Book(); book.Name = "Service Design Patterns"; book.PublisherId = 2; context.Books.Add(book); context.SaveChanges(); }
For this last approach to work, I needed to add an additional property PublisherId, it should be named according to the NavigationPropertyName + 'Id' convention, which should be selected by EF auotmatically:
public int PublisherId { get; set; } public Publisher Publisher { get; set; }
I use the EF5 code here first, but it is very similar to POCO.
Sebastian k
source share