Reputation:
I am writing an application using MVC2 and EF4. I have created entities from my Database, I have a Timesheet table and a TimesheetEntry table.
I am using the Model binding features of MVC2 and successfully receiving a Timesheet object with its TimesheetEntries populated with the TimesheetEntries created by the user.
If I use the technique I have used in other methods (here timesheet is the object created by the MVC framework):
Timesheet temp = context.Timesheets
.Include("TimesheetEntries")
.Where(t => t.Id == timesheet.Id).First();
context.ApplyCurrentValues<Timesheet>(temp.EntityKey.EntitySetName, timesheet);
context.SaveChanges();
Then my TimesheetEntries are not saved.
I have been trying without any success to do this by other means, like deleting all the entries:
Timesheet temp = context.Timesheets
.Include("TimesheetEntries")
.Where(t => t.Id == timesheet.Id).First();
context.ApplyCurrentValues<Timesheet>(temp.EntityKey.EntitySetName, timesheet);
context.ExecuteStoreCommand(@"DELETE FROM TimesheetEntry WHERE Timesheet=" + timesheet.Id.ToString());
foreach (TimesheetEntry entry in timesheet.TimesheetEntries)
{
entry.Timesheet = timesheet.Id;
context.TimesheetEntries.AddObject(entry);
}
context.SaveChanges();
return Redirect("ListTimesheets?PersonnelId="+timesheet.Person);
This is not working properly, I am still not getting TimesheetEntries into the DB :-( Just wondering if iam barking up the wrong tree here all together?
P.S. if any one want more info on any of these things let me know. and I can post more code.
Upvotes: 2
Views: 1952
Reputation:
again here timesheet is the class created by the MVC mapping
Timesheet DBTimesheet = context.Timesheets
.Include("TimesheetEntries")
.Where(t => t.Id == timesheet.Id).First();
//Delete if in database but not in submission
DBTimesheet.TimesheetEntries
.Where(dbE => !timesheet.TimesheetEntries.Any(e => e.Id == dbE.Id)).ToList()
.ForEach(dbE => context.TimesheetEntries.DeleteObject(dbE));
//Update if in submission and in database
timesheet.TimesheetEntries
.Where(e => DBTimesheet.TimesheetEntries.Any(dbE => dbE.Id == e.Id)).ToList()
.ForEach(e => context.TimesheetEntries.ApplyCurrentValues(e));
//Add if in submission but not in database
timesheet.TimesheetEntries
.Where(e => !DBTimesheet.TimesheetEntries.Any(dbE => dbE.Id == e.Id)).ToList()
.ForEach(e => DBTimesheet.TimesheetEntries.Add(e));
context.SaveChanges();
Updates, Deletes and Adds referenced classes as required, NOT FULLY TESTED
Upvotes: 4
Reputation: 126547
Read the documentation for ApplyCurrentValues
; it does scalar properties only.
But you can do:
Timesheet temp = context.Timesheets
.Include("TimesheetEntries")
.Where(t => t.Id == timesheet.Id).First();
context.ApplyCurrentValues<Timesheet>(temp.EntityKey.EntitySetName, timesheet);
foreach(var tse in timesheet.TimesheetEntries)
{
temp.TimesheetEntries.Add(tse); // or update, if need be.
}
context.SaveChanges();
Upvotes: 3