Matt Roberts
Matt Roberts

Reputation: 26917

EF Code first - Adding many-to-many record, nothing is being saved

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);
}

Upvotes: 0

Views: 337

Answers (1)

Matt Roberts
Matt Roberts

Reputation: 26917

Ok, the problem was I wasn't attaching my installer object to the context...

This works:

var installer = installerModel.Installer;
context.Installers.Attach(installer);

foreach (var permittedMasterInstanceId in installerModel.SelectedMasterInstances)
{
    if (!installer.PermittedMasterInstances.Any(pmi => pmi.MasterInstanceId == permittedMasterInstanceId))
    {
        var masterInstance = new MasterInstance {MasterInstanceId = permittedMasterInstanceId};
        context.MasterInstances.Attach(masterInstance);
        installer.PermittedMasterInstances.Add(masterInstance);
    }
}

Upvotes: 1

Related Questions