c# - Entity Framework - force commit without transaction -
i have loop looks bit this:
countstoreport = rep.counts_get().where(x => x.status == "completed"); foreach (var count in countstoreport.tolist()) { //do stuff //send email count.status = "reported"; rep.savechanges(); }
where "rep" repository wrapper around ef context.
when runs, unfortunate email recipient gets deluged spam because savechanges call doesn't commit changes - loop keep getting same counts, emailing them, , marking them "reported" doesn't save change.
if stop loop, , re-start code, change saves successfully. can confirm scenario stepping through code: ef object in c# changes status, underlying data in sql doesn't change.
i'm presuming because savechanges doesn't commit transaction - marks data having changed ready end of transaction. we're not using transactions anywhere else in db, , it'd bit of pain change repository 1 use case.
is there other way can force ef commit change , escape endless loop of doom? or mistaken cause?
edit: putting in repository , calling instead of savechanges fixes it:
public void savewithtransaction() { using (var transaction = new system.transactions.transactionscope()) { db.savechanges(); transaction.complete(); } }
but seems ugly. still interested know if there's way round.
edit: deceptive. looks it's old add/modified problem again. marking object modified seems help.
it quite possible entities in countstoreport detached context. not changetracker doesn't see sort of change done on count, doesn't know entity @ all.
to have issue fixed:
- iterate through collection of countstoreport
- attach each entity context,
db.counts.attach(count)
- modify count.status , call db.savechanges();
like this:
foreach (var count in countstoreport.tolist()) { //do stuff //send email rep.counts.attach(count); count.status = "reported"; rep.savechanges(); }
have @ following link more information entity states , how deal them: http://msdn.microsoft.com/en-us/data/jj592676.aspx
Comments
Post a Comment