I’m using EF 4.3 code-first. I have a many-to-many relationship. I am trying in code to attach and save my related records from an array of ids. Ideally I don’t want to load those related entities before I save them…
Here is my model – Installers can have many MasterInstances:
public class MasterInstance
{
public int MasterInstanceId { get; set; }
[Required] public string HostName { get; set; }
[Required] public string Name { get; set; }
[Required] public string ConnectionString { get; set; }
public virtual ICollection<MasterInstanceLocation> MasterInstanceLocations { get; set; }
public ICollection<Installer> PermittedInstallers { get; set; }
}
public class Installer
{
public int InstallerId { get; set; }
[Required] public string UserName { get; set; }
[Required] public string Password { get; set; }
public ICollection<MasterInstance> PermittedMasterInstances { get; set; }
}
In my code, I am trying to attach the master instances to the installer :
installer.PermittedMasterInstances = new List<MasterInstance>();
foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances)
{
var masterInstance = new MasterInstance {MasterInstanceId = permittedMasterInstanceId};
context.MasterInstances.Attach(masterInstance);
installer.PermittedMasterInstances.Add(masterInstance);
}
context.Entry(installer).State = EntityState.Modified;
context.SaveChanges();
But.. Nothing is being written to the link table 🙁 Any ideas why?
EDIT
The only thing that works is this rather unpleasant solution… Is this the only way?
foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances)
{
var masterInstance = context.MasterInstances.Single(mi => mi.MasterInstanceId == permittedMasterInstanceId);
masterInstance.PermittedInstallers = new List<Installer>();
context.MasterInstances.Attach(masterInstance);
masterInstance.PermittedInstallers.Add(installer);
installer.PermittedMasterInstances.Add(masterInstance);
}
Ok, the problem was I wasn’t attaching my installer object to the context…
This works: