Linq - 数据库中的行不会删除

时间:2016-03-16 14:44:52

标签: c# linq

寻找linq的一些帮助。我正在陷入困境,因为我认为我正在做一些根本错误的事情。

这是背景。

我有一个活动列表的用户 - 活动有一个" ActivityDateTime"

所以,我试图做的事应该很容易。我正在尝试检索具有特定日期的活动列表的用户,并且"替换"任何现有的新的...

但我陷入了混乱......

这是我的代码:

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

    }

我知道我一团糟。任何人都可以帮我找到出路吗?

这是我的表在运行上述代码3次后在数据库中的样子......

enter image description here

1 个答案:

答案 0 :(得分:1)

您是否在此行代码后检查了实体的State属性?

 user.Activities.RemoveAll(x => activitiesToRemove.Contains(x));

所有这些项目都有可能未被跟踪,这就是为什么可能在SaveChanges()上发生的事情。

尝试这种方式强制状态为已删除。通常在这里工作:)

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

然后db.SaveChanges();