Why isn't my value stored in the database with LINQ?
I'm using the following LINQ-statement to update a table-entry with the current date/time:
MembershipClassesDataContext db = new MembershipClassesDataContext();
var tmp = db.drun_addqol_2_usrs.SingleOrDefault(y => !y.done.HasValue && y.UserId.Equals(Membership.GetUser().ProviderUserKey.ToString()));
tmp.done = DateTime.Now;
// at this point, tmp.done has the correct value!
// also the entry isn't null because I got the correct ID with tmp.UserId
// But db.GetChangeSet().Count is zero (0), so the value of "done" is changed but not commited to the ChangeSet?!开发者_如何学JAVA
db.SubmitChanges();
"done" is a column with type DateTime and after the above query it shouldn't be null but should contain the actual date / time. But... it doesn't update and the value is still null.
Any ideas where my mistake is?
Thanks in advance!
Is the object being returned from SingleOrDefault one that already exists in the DB, or a new default object? if it's a new then you have to add it to the dataset or .submitchanges will not save it.
Before you call db.SubmitChanges(), call db.GetChangeSet() to determine if L2S thinks it has any rows to update. If the changeset is empty then your SingleOrDefault() method must be returning nothing.
Stupid question - In the designer code for your drun_addqol_2_usrs, does the if statement for the setter evaluate to true (and call the property changed stuff)?
set
{
if ((this._done != value))
{
this.OndoneChanging(value);
this.SendPropertyChanging();
this._done = value;
this.SendPropertyChanged("done");
this.OndoneChanged();
}
}
I wonder if tmp is attached to your datacontext?
Try -
db.drun_addqol_2_usrs.Attach(tmp)
and then call
SubmitChanges()
it'll either work, or it'll throw an exception complaining that it can't attach an entity to a data context when it's already attached to a data context, or something like that.
精彩评论