Reputation: 3954
Looking for some help with linq. I am getting in a right muddle as I think I am doing something fundamentally wrong.
This is the background.
I have a user with a list of activities - the activities have an "ActivityDateTime"
So, what I am attempting to do should be quite easy. I am trying to retrieve a user with a list of activities for a particular date and "replace" any existing ones with the new ones...
But I am getting in a right mess..
here is my code:
public static bool UpdateDailyActivity(string emailAddress, DateTime activityDate) {
// get a user
using (DataModel db = new DataModel()) {
DataUser user = db.DataUsers
.Include("AuthData")
.Include("Activities")
.Include("Activities.activities")
.Include("Activities.goals")
.Include("Activities.summary")
.Include("Activities.summary.distances")
.Where(x => x.Email == emailAddress).FirstOrDefault();
// Get a list of todays activities already in the user
List<Activity> todaysActivities = user.Activities
.Where(x => x.ActivityDateTime >= activityDate.Date && x.ActivityDateTime < activityDate.AddDays(1).Date)
.ToList();
// remove the activities from the user
var activitiesToRemove = new HashSet<Activity>(todaysActivities);
user.Activities.RemoveAll(x => activitiesToRemove.Contains(x));
// save the user to try and remove the current activities
db.SaveChanges(); // <- this is leaving the rows behind
// get the activity data
Activity activityData = GetDailyActivity(user, activityDate);
if (activityData != null) {
// update this days activity for this user
user.Activities = new List<Activity>();
user.Activities.Add(activityData);
// save the changes
db.SaveChanges();
// everything worked ok
return true;
} else {
// failed
return false;
}
}
}
I know I am in a mess. Can anyone help me find my way out?
This is what my table looks like in the database after running the above code 3 times...
Upvotes: 0
Views: 49
Reputation: 3321
Have you checked the State property of the entity after this line of code?
user.Activities.RemoveAll(x => activitiesToRemove.Contains(x));
There's a chance that all this items are Untracked, that's why probably nothings happen on SaveChanges().
Try this way forcing the State to Deleted. Usually works here :)
// Get a list of todays activities already in the user
List<Activity> todaysActivities = user.Activities
.Where(x => x.ActivityDateTime >= activityDate.Date && x.ActivityDateTime < activityDate.AddDays(1).Date)
.ToList();
// remove the activities from the user
foreach (var a in todaysActivities)
{
db.Entry(a).State = EntityState.Deleted;
}
and then db.SaveChanges();
Upvotes: 1