Update multiple fields of a record using Linq and EF not working

I have a ridiculous problem with updating a record of SQL DB. I wrote a function which update My db using an EF data model as below:

public static void UpdateEventTime(int ID, int year, int month, int day, int hour, int minute, int duration)
{
  (from e in SchedulerDatabase.Events where e.ID == ID select e).Single().Duration = duration;
  SchedulerDatabase.SaveChanges();
}

this works perfectly but when I try to update multiple fields like this:

public static void UpdateEventTime(int ID, int year, int month, int day, int hour, int minute, int duration)
{
  Event E = (from e in SchedulerDatabase.Events where e.ID == ID select e).Single();
  E.StartDate = new DateTime(year, month, day, hour, minute, 0);
  E.Duration = duration;
  SchedulerDatabase.SaveChanges();
}

It doesn't work! But if I put a breakpoint there and run it again, It shows that EF is updated cause E.Duration holds the updated value(not the value in DB), but it does not update the database! What am I doing wrong? Does it update just one field?!(If I delete E.StartDate = ... Line it works and updates the DB) or is there any problem with datetime?!

Upvotes: 2

Views: 932

Answers (1)

Seany84
Seany84

Reputation: 5596

1. Just out of curiosity.. what are the values you have passed in for year, month, day, hour and minute? Could it be a case that you are passing invalid parameter values in?

2. I think you need to let EF know that you are making a change to the state of the object.

I don't have Visual Studio to hand but can you try the following:

public static void UpdateEventTime(int ID, int year, int month, int day, int hour, int minute, int duration)
{
  Event E = (from e in SchedulerDatabase.Events where e.ID == ID select e).Single();
  E.StartDate = new DateTime(year, month, day, hour, minute, 0);
  E.Duration = duration;
  SchedulerDatabase.Entry(E).State = EntityState.Modified;
  SchedulerDatabase.SaveChanges();
}

Upvotes: 1

Related Questions