简体   繁体   English

实体框架不将更改保存到数据库中

[英]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? 我很困惑为什么这个代码不起作用,它应该在循环之后保存对数据库的更改但是当我将SaveChanges方法放在循环中时,它将记录保存到数据库中但是在它之外它不保存任何东西? it's about only 300 ~ 1000 records 它只有300~1000条记录

    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? 所以我将记录限制为100并保存更改有效,瞬间3000条记录不起作用,任何解决方案?

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 注意:这在添加1200条记录和300条修改时适用于我

 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; 你可以使用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 实体框架6提供了AddRange()这将一次性插入项目,它将禁用AutoDetectChangesEnabled并插入实体

In your case you don't want to mark the entites as Modified, the EF already tracks it well. 在您的情况下,您不希望将entites标记为已修改,EF已经很好地跟踪它。 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. 仅仅因为等待saccldb.SaveChangesAsync()的异步性质导致您的线程继续并在保存到db完成之前退出该函数。 In your case it returns true. 在您的情况下,它返回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. 我建议不要在控制台应用程序上使用任何异步操作,除非它有一个你想继续使用的用户界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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