开发者

LInq update is also inserting unwanted rows

I am new to Linq to SQL, but I am surprised at the problems I am having updating a table. From reading various sources I think the problem I get is a problem with the ORM mapping, but even so, given I am using VS 2008 and creating my dbml via a LINQ to SQL class, I do not expect this. So what is happening is that when I update and/or insert a row, lots of other rows get created in the table as well. I cannot predict what the pattern is when this happens, sometimes it doesn't happen. I am not sure the code below says very much about what the problem is, but I reproduce it here;

    public static void UpdateDailyTimeRecorded(
        int dailyTimeRecordedId, bool amFlag, string timeIn, string timeOut)
    {
        DailyTimeRecorded dtr = GetDailyTimeRecorded(dailyTimeRecordedId);
        if (amFlag == true)
        {
            dtr.MorningTimeIn_HH = Convert.ToInt32(timeIn.Substring(0, 2));
            dtr.MorningTimeIn_MM = Convert.ToInt32(timeIn.Substring(3, 2));
            dtr.MorningTimeOut_HH = Convert.ToInt32(timeOut.Substring(0, 2));
            dtr.MorningTimeOut_MM = Convert.ToInt32(timeOut.Substring(3, 2));
            dtr.MorningLeaveFlagId = 0;
        }
        else
        {
            dtr.AfternoonTimeIn_HH = Convert.ToInt32(timeIn.Substring(0, 2));
            dtr.AfternoonTimeIn开发者_如何学Go_MM = Convert.ToInt32(timeIn.Substring(3, 2));
            dtr.AfternoonTimeOut_HH = Convert.ToInt32(timeOut.Substring(0, 2));
            dtr.AfternoonTimeOut_MM = Convert.ToInt32(timeOut.Substring(3, 2));
            dtr.AfternoonLeaveFlagId = 0;
        }
        try
        {
            db.SubmitChanges();
        }
        catch (ChangeConflictException)
        {
            db.ChangeConflicts.ResolveAll(RefreshMode.KeepChanges);
        }
    }

I put a breakpoint on the line db.SubmitChanges(); and the rows get inserted at this point for sure, not before and not some code afterwards.


One cause that I'm aware of off the top of my head that might cause LINQ to insert unexpected data is this. Even though you don't explicitly add a row of data to a particular table, LINQ to SQL will implicitly add it if you have it linked to another object that you have explicitly added.

Another cause is that you cannot readily rollback or undo pending changes added to a context. My understanding is that the best practice is to dispose of the context containing the unwanted objects and start a new one if and when you realize that you didn't want to perform the update.


Call DataContext.GetChanges() and see what else is captured. It might be from a previous 'non-committed' action on the data context.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜