MVC4 EF5 eager load table然后附加到另一个表

时间:2013-12-04 13:25:55

标签: entity-framework asp.net-mvc-4

MVC4 EF5

我有2个表步骤和任务

public class Step {
public int StepID { get; set; }
public string StepName { get; set; }
public int Stepseq { get; set; }

public int BuilderID { get; set; }
public virtual Builder Builder { get; set; }
}

public class Task {
public int TaskID { get; set; }
public string StepName { get; set; }
public int Stepseq { get; set; }
public DateTime? SStart { get; set; }

public int BuilderID { get; set; }
public virtual Builder Builder { get; set; }
}

步骤包含大约100行。我需要从步骤中读取行,并将100个新行追加(插入,添加)到Task表中,将StepName和StepSeq值复制到附加行中。 我有一个包含两个集合的StepTask模型:

public class StepTask    {
public virtual ICollection<Step> Steps { get; set; }
public virtual ICollection<Task> Tasks { get; set; }
}

现在请一些帮助。我认为这将加载100步

var mycontext = new HouseContext   // contains DbSet for step, task and steptask
{ var AllSteps =  mycontext;
.Step
// now loop through the 100 and assign values 
foreach (var mystep in AllSteps)  
{
mycontext.Task.StepName = mystep.StepName
mycontext.Task.StepSeq = mystep.StepSeq
mycontext.Task.BuilderID = mystep.BuilderID
// and save each row    OR move outside foreach loop and save when finished.
mxcontext.SaveChanges()
}
// done ?
}

当我在VS2012中使用它时,Intellisence不会在mycontext.Tasks.StepName中显示StepName。它确实看到mycontext.Tasks和.Steps。这告诉我某些事情没有被正确宣布。

.SaveChanges是否应该在[每行]的循环内或者在添加所有100之后? BuilderID是否正确处理?
mycontext.Tasks vs mycontext.Task有问题吗? 感谢

1 个答案:

答案 0 :(得分:1)

StepsTasks都是收藏品。您需要创建新的Task个实例并将其添加到Tasks

using(var mycontext = new HouseContext())
{
    foreach (var mystep in mycontext.Steps)  
    {
        Task task = new Task();
        task.StepName = mystep.StepName
        task.StepSeq = mystep.StepSeq
        task.BuilderID = mystep.BuilderID
        mycontext.Tasks.Add(task);
    }
    mycontext.SaveChanges()
}
最后应该调用

SaveChanges。如果您正在处理数千条记录,那么您应该每百个左右提交一次并创建一个新的HouseContext每千个左右...