简体   繁体   中英

Entity Framework not Saving Changes into Database

I'm puzzled as to why this code is not working, it should save changes to database after the loops but when I place the SaveChanges method inside the loop, it saves the record into the database but outside it doesn't save anything? it's about only 300 ~ 1000 records

    static bool lisReady = false;
    static bool sacclReady = false;

    static void Main(string[] args)
    {
        Logger("Starting services");
        ConnectDBLis().Wait();
        ConnectDBSaccl().Wait();
        Thread.Sleep(1000);
        if (lisReady & sacclReady){
            //start
            Logger("Services ready");
            StartExport().Wait();
        }
    }

    static async Task<bool> StartExport()
        {
            lis lisdb = new lis();
            nrlsaccl saccldb = new nrlsaccl();
            var getTestOrders = await lisdb.test_orders.ToListAsync();
            Logger("Services starting");
            foreach (var tO in getTestOrders.Where(x => x.entry_datetime.Value.Year == 2016))
            {
                foreach (var tr in tO.test_results)
                {
                    foreach (var tL in tr.test_result_logs)
                    {
                        results_availability postResults = new results_availability
                        { 
                          first_name = tO.patient_orders.patient.first_name,
                          middle_name = tO.patient_orders.patient.middle_name,
                          last_name = tO.patient_orders.patient.last_name,
                          birthdate = tO.patient_orders.patient.birthdate,
                        };
                        if (postResults.id == 0)
                        {
                            saccldb.results_availability.Add(postResults);
                        }
                        else
                        {
                            saccldb.Entry(postResults).State = EntityState.Modified;
                        }
                    }
                }
            }
            await saccldb.SaveChangesAsync();
            return true;
        }

Edit:

So i limit the records to 100 and the save changes works, 3000 records at instant does not work, any solutions?

This code doesn't completely resolve your issue, this are some consideration for your problem.

Note: This works for me when adding 1200 records and 300 modifications

 static async Task<bool> StartExport()
    {
        using (var db = new Entities())
        {
            var appraisals = await db.Appraisals.ToListAsync();

            db.Database.CommandTimeout = 300;
            //Disabling auto detect changes enabled will bring some performance tweaks
            db.Configuration.AutoDetectChangesEnabled = false;
            foreach (var appraisal in appraisals.Where(g => g.Id > 1))
            {

                if (appraisal.Id == 10)
                {
                    appraisal.AppraisalName = "New name";
                    db.Entry(appraisal).State = EntityState.Added;
                }
                else
                {
                    appraisal.AppraisalName = "Modified name";
                    db.Entry(appraisal).State = EntityState.Modified;
                }
            }

            db.Configuration.AutoDetectChangesEnabled = true;

            if (await db.SaveChangesAsync() > 1)
                return true;
            else
                return false;
        }
    }

You could use db.Database.CommandTimeout = 300; to increase the timeout of you connection.

Entity framework 6 provides AddRange() This will insert the items in one shot, it will disable AutoDetectChangesEnabled and insert the entities

In your case you don't want to mark the entites as Modified, the EF already tracks it well. Entity Framework - Why explicitly set entity state to modified?

The purpose of change tracking to find that you have changed a value on attached entity and put it to modified state. Setting state manually is important in case of detached entities (entities loaded without change tracking or created outside of the current context).

Here we have all entities attached to the context itself

Use

saccldb.SaveChanges()

Simply because the async nature of await saccldb.SaveChangesAsync() cause your thread to continue and exit the function before the saving to the db completes. In your case it returns true.

I would suggest not using any async operations on a console application unless it has a user interface that you would want to keep going.

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