使用其他 table 中存在的数据更新联结 table

Updating a junction table with data that is present in the other tables

我有这两个table

public partial class Items
{
    public Items()
    {
        this.Variables = new HashSet<Variable>();
    }

    public int Id { get; set; }
    public string name {get; set};
    //other columns 

    public virtual ICollection<Variable> Variables { get; set; }
  }
}

public partial class Variable
{
    public Variable()
    {
        this.Items= new HashSet<Items>();
    }

    public int Id { get; set; }
    public string name {get; set};
    //other stuff

    public virtual ICollection<Items> Items{ get; set; }
 }
}

tr 这些都是首先从数据库自动创建的 Entity Framework(从 edmx 文件中的数据库更新模型)。我需要能够更新从

创建的联结 table
public virtual ICollection<Template> Templates { get; set; }
public virtual ICollection<Variable> Variables { get; set; }

连接点 table 只是两列 TemplateId 和 VariableID,它们都是各自 tables.These 的外键,需要匹配项和变量的名称。目前我能够完成一些工作(我没有从项目 Table 中获得 ID):

foreach (var tempItem in db.Items)
           {

               var item = db.Variables.FirstOrDefault(x => x.Name tempItem.Name);
                db.Variables.Add(item);

            }
            db.SaveChanges();

编辑:sql 我想要完成的是:

select Top 1000 V.ID, I.ID
FROM [PageflexWeb].[dbo].[Variables] as V, [PageflexWeb].[dbo].[Items] as I
Where V.Name = I.Name

效果很好,但我需要一种方法将其保存到交界处 table dbo.ItemVariables

如有任何帮助,我们将不胜感激。

我已经通读了所有关于 msdn 和 stack 的文档,但我找不到我要找的答案。

Db.Templates.Add(newItem);
foreach (var record in variable.Where(record => record.Name == newItem.Name))
    {
         record.Templates.Add(newItem);
    }

}
Db.SaveChanges();

所以我需要将 newItem 添加到项目 table - 然后加载记录并通过它们建立关系。除非有另一种自动更新方式(changeTracking?),否则我将把它标记为答案。谢谢@Robert McKee