简体   繁体   中英

EF Code-First doesn't update Sets immediately

I'm developing an ASP.NET MVC 3 website with Entity Framework Code-First. What's happening is that in the Index action, I get some TransactionJournal objects from the database, call a method called CreateTransactions(), that, basically, create some transactions and add them to the ICollection in the TransactionJournal. Then, I save the context, and then query for all Transactions, and then they are not there, But if I just refresh the page, I will get the transactions generated at the first time, that didn't appear. but not the ones from this time, There's a lot of code, so. I'll try to mock the parts that are important here so that you can see.

A piece of the TransactionJournal:

public class TransactionJournal {
    public long TransactionJournalID { get; set; }
    public virtual ICollection<Transaction> Transactions { get; set; }
    // ...
}

A piece of the Index action:

IDbSet<TransactionJournal> journal_dbset = Context.Set<TransactionJournal>();
ICollection<TransactionJournal> journals = journal_dbset.Where( ... ).ToList();

foreach(TransactionJournal j in journals)
    j.CreateTransactions(); // Create some transactions and add it to the Transactions collection

Context.Commit(); // This actually calls the SaveChanges() method, only

IDbSet<Transaction> trans_dbset = Context.Set<Transaction>();
ICollection<Transaction> trans = trans_dbset.Where( ... ).ToList(); // The transactions just created are NOT here! But those created in previews Index action calls are!

It's like if the SaveChanges() don't immediately updates the Sets in the Context object. What should I do to get these just created transactions?

In CreateTransactions did you make a call to flag the object in the context to be updated?

context.Entry(j).State = EntityState.Modified;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM