开发者

Why can't I update data into database using LINQ to SQL?

开发者 https://www.devze.com 2023-03-28 04:00 出处:网络
I am trying to update data while I am reading them from database, see below. But after the whole thing finish, the data didn\'t get updated.(my table has primary key ).

I am trying to update data while I am reading them from database, see below. But after the whole thing finish, the data didn't get updated.(my table has primary key ).

    static LinqMPISMPPCalenderDataContext DBCalender;
   开发者_开发百科 DBCalender = new LinqMPISMPPCalenderDataContext(connectionString);
    var ExceptionPeriod= DBCalender.Table_ExceptionPeriods
    .Where(table=>Table.StartDate<= Date && table.FinishDate >= Date && table.CalenderID==CalenderID).Single();

    Table_ExceptionPeriod TblException =null;
    TblException = ExceptionPeriod;
    TblException.StartDate = ExceptionPeriod.StartDate.AddDays(1);
    DBCalender.SubmitChanges();


Once you've got your object from the DB via your .Single() call you should be able to just set properties on it and call SubmitChanges(). There's no need for the TblException stuff. So ...

static LinqMPISMPPCalenderDataContext DBCalender;
DBCalender = new LinqMPISMPPCalenderDataContext(connectionString);
var ExceptionPeriod = DBCalender.Table_ExceptionPeriods
    .Where(table=>Table.StartDate<= Date && table.FinishDate >= Date && table.CalenderID==CalenderID).Single();

ExceptionPeriod.StartDate = ExceptionPeriod.StartDate.AddDays(1);
DBCalender.SubmitChanges();


There doesn't seem to be anything logically wrong with the code, as Antony says you could reduce the number of lines.

I'd probably step through the code line by line, before the submit line check if the StartDate has actually changed.

Only things I can imagine that could be going wrong are some kind of transaction roll back in the database or you're not looking at the record you think you are.

0

精彩评论

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

关注公众号