开发者

EF Calling SaveChanges() Mutipletimes

We are building a Employee Time-Tracking program which has fields such as

------------------------
Employee Number: 2001
Time in: 9am
Time out: 5pm
Overtime: 0
------------------------

The client would like the option to ADD FOR ENTIRE WEEK CheckBox so they can enter data once and checkbox to all for entire week.

The business logic is crazy and I just need to call the SAVECHANGES() 5 times.

Question: How to I call the ctx.SAVECHANGES(); multiple times? I have tried a ForEach and I have tried copy/paste ctx.SAVECHANGES(); several times without any luck.

开发者_如何学运维TIA


That should work. A second call to SaveChanges() would only have no effect if you did not make any changes to your entity set after the last SaveChanges(). But in general you will not have to call SaveChanges() more than once, because a single call will commit all changes.

Since you didn't specify your entities let's Imagine you have an Employee Entity and a TimeSheet Entity. The TimeSheet Entity has a foreign key relationship with the Employee Entity.

Then something like this should work:

using(var context = new TimeTrackingEntities())
{
  var emp = context.Employees.Where(x=>x.Id == 2001).Single();
  DateTime day = DateTime.Now.Date;

  for(int i=0;i<7; i++)
  { 
     TimeSheet t = new TimeSheet() {Employee = emp, Day = day, OtherProperties="here"};
     day = day.AddDays(1);
     context.TimeSheets.Add(t);
  }
  context.SaveChanges(); // save all timesheet additions
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜