首先是EF代码 - 添加多对多记录,不保存任何内容

时间:2012-01-31 09:37:40

标签: c# entity-framework entity-framework-4

我正在使用EF 4.3代码优先。我有多对多的关系。我正在尝试在代码中附加并保存来自一组id的相关记录。理想情况下,我不想在保存之前加载这些相关实体......

这是我的模型 - 安装人员可以拥有许多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; }
}

在我的代码中,我尝试将master instances附加到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();

但..没有任何内容写入链接表:(任何想法为什么?

修改

唯一有效的是这种相当不愉快的解决方案......这是唯一的方法吗?

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

1 个答案:

答案 0 :(得分:1)

好的,问题是我没有将我的安装程序对象附加到上下文...

这有效:

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