1

MVC4 EF5

I have 2 tables Steps and Tasks

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

Step contains about 100 rows. I need to read the rows from step, and append (insert, add) 100 new rows to the Task table copying the StepName and StepSeq values into the appended rows. I have a StepTask Model that includes both collections:

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

Now some help please. I think this will load the 100 steps

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 ?
}

As I work with this in VS2012 Intellisence does not show the StepName in mycontext.Tasks.StepName. It does see mycontext.Tasks and .Steps. This tells me something is not declared properly.

Should the .SaveChanges be within the loop [for each row] or after all 100 are added?
Is the BuilderID properly handled?
Do I have a problem with mycontext.Tasks vs mycontext.Task ?
Thanks

user2887440
  • 51
  • 1
  • 8

1 Answers1

1

Steps and Tasks are both collections. You need to create new Task instances and add them to 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 should be called at the end. If you are processing thousands of records then you should commit every hundred or so and create a new HouseContext every thousand or so ...

qujck
  • 14,388
  • 4
  • 45
  • 74
  • See [here](http://stackoverflow.com/questions/5940225/fastest-way-of-inserting-in-entity-framework) for more information on bulk loading with Entity Framework – qujck Dec 04 '13 at 13:43
  • @user2887440 you should be able to see a hollow tick to the left of my answer. Just mouse click this tick to mark it as the answer. – qujck Dec 05 '13 at 15:36