System.OutOfMemoryException使用实体框架? [英] System.OutOfMemoryException using Entity Framework?

查看:87
本文介绍了System.OutOfMemoryException使用实体框架?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Entity框架保存数十万条记录.保存数十万条记录后,出现以下错误:

I am trying to save hundreds of thousands of records using Entity framework. After saving few hundreds of thousands of records I get following error:

:System.OutOfMemoryException

:System.OutOfMemoryException

我的代码

  foreach (BibContent objbibcontents in lstBibContent)
        {
            db.BibContents.AddObject(objbibcontents);
            c = c + 1;
            if (c == 1000)
            {
                db.SaveChanges();
                c = 0;
            }
        }

我注意到保存1000条记录后,我的数据库没有覆盖其他1000条记录.它将它们添加到我的dbcontext中.

I noticed after saving 1000 records my db is not overriding another 1000 records. it is adding them into my dbcontext.

我要在1000条记录之后创建一个新实例,但是我的数据库仍然具有先前对象的数据.看看我的代码

I am creating a new instance after 1000 records but my db still has the previous object's data. See my code

   foreach (var objbibcontents in lstBibContent)
            {
                vibrantEntities db1 = new vibrantEntities(szConStr);
                lstBibCon.Add(objbibcontents);
                // db.BibContents.AddObject(objbibcontents);
                c = c + 1;
                if (c == 1000)
                {
                    foreach (BibContent bibobject in lstBibCon)
                    {
                        db1.BibContents.AddObject(bibobject);
                    }
                    lstBibCon.Clear();
                    db1.SaveChanges();
                    c = 0;
                    flag = 1;
                }
            }

推荐答案

您要保存多少个对象,单个对象的大小是多少? DbContext保存对通过AddObject调用添加的所有对象的引用.调用SaveChanges不会清除其内部数据结构,因此,如果为1M对象调用代码,则内存中将有1M对象,并且它们将完全处于活动状态,因为它们的GC根对象将是上下文实例,该实例仍在以下范围内您的运行代码.

How many objects are you going to save and how big is single object? DbContext holds references to all objects you added with AddObject call. Calling SaveChanges does not purge its internal data structures so if you call your code for 1M objects you will have 1M object in memory and they will be fully alive because their root object for GC will be the context instance which is still in scope of your running code.

如果要避免内存问题,则应为每1000条记录(甚至每条记录)使用一个新的上下文实例.为单个记录运行SaveChanges与为单个记录运行之间的唯一区别是自动涉及的事务.

If you want to avoid the memory issue you should use a new context instance for every 1000 records (or even every record). The only difference between running SaveChanges for 1000 records and for single record is the automatically involved transaction.

这篇关于System.OutOfMemoryException使用实体框架?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆