I’m using WCF Data Services which is working well for most things, but I’m having trouble figuring out how to update an entity that has a related entity collection. For example, in the code below I have a Batch object which has related Departments. In my database this is represented as three tables – Batches, Departments, and Batches_Departments. EF exposes this to me as Batch object with navigation property for Departments.
In the code listed below the Batch object is created and the Departments collection is populated, but when I call SaveChanges, only the Batch object is created in the database. The Departments are ignored. If I set a breakpoint on the SaveChanges line, I can verify the Departments collection is populated.
private void Save()
{
var batch = new DataService.Batch() { Description = txtDescription.Text, Filename = txtFilename.Text };
foreach (var department in lstDepartments.CheckedItems)
{
var dept = _ctx.Departments
.Select(d => d)
.Where(d => d.DepartmentID == ((DataService.Department)department).DepartmentID)
.First();
batch.Departments.Add(dept);
}
_ctx.AddToBatches(batch);
_ctx.SaveChanges();
}
I’m sure I’m missing something obvious, but I can’t seem to find it. Any help will be appreciated.
This is a limitation in the current generated code. You will also need to add the following line of code to your program:
You could also hook into the PropertyChanged event for batch if you prefer.
Edit: I found another option as well. You can do the following rather than
AddLink: