Entity Framework 4 - Adding an existing model to an association
I have defined a relationship, which is a module can contain many courses.
I have an interface which al开发者_如何学JAVAlows you to add course to module; I have tried the code below, but this results in a new module being created in the modules table, and then added to the course
int moduleID = viewModel.moduleID;
course.Modules.Add( new Module { ID = moduleID } )
SaveChanges();
What should be the proper way?
Edit: Debugging with breakpoints show that the integer moduleID is correct.
You can try this:
var module = new Module { ID = viewModel.moduleID };
// Attach first so that context doesn't track module as a new one
context.Modules.Attach(module);
// Now make connection to attached module
course.Modules.Add(module);
context.SaveChanges();
As you can see I didn't need to load module from database to make a connection. This works quite good for many-to-many relations but can be more complicated in case of one-to-many relations.
You are creating a new module, which means that the behaviour you're getting is normal. What you need to do is, get the Module
object that corresponds to the moduleID
from your data context and then add that to your course.
int moduleID = viewModel.moduleID;
var module = context.Modules.FirstOrDefault(m => m.ID == moduleID);
course.Modules.Add(module)
SaveChanges();
Hope this helps :)
精彩评论