Home » .Net Framework

Adding an Entity to the objectContext via AddObject being Very slow

We've just converted our code over to start using our own POCOs instead of generated Entities.  We're pretty excited.  In our program we've found some snags where certain of our larger objects take so long(5-10 seconds) to be added to the ObjectSet that our webserver times out.  This isn't a problem across the board (in most places, saving takes  the amount of time that we are used to), but this slowness is a dealbreaker.  

Are there things that we need to be aware of that we might be doing wrong?


4 Answers Found


Answer 1

Do you see the issue when using the generated  entities?

Answer 2


There are several considerations about performance in entity  Framework: lazy loading, pre-generated views, tracking and so on. In your case, there seems a timeout issue, I would suggest you build the connection manually. what I mean is to build the EntityConnection manually using ConnectionStringBuilder which demostrated here. Sometimes, this could cut off half the time  it spend.

For more performance considerations in Entity Framework, please read this documentation:

Best regards


Answer 3

After more debugging, we've decided that our problem  likely lies with WCF RIA Services instead of EF.  Thanks for your help, sorry that my problem is so vague.  We still don't know what's going on though


See our question in the WCF RIA forums:



Answer 4

Thanks for your reply!

But with the description in the post, it's really hard to find out where the root cause is. Would you please generate a small project to reproduce and send the project to my email? I'll try my best to help you. My email account is v-roaluoATmicrosoftDOTcom.

Best regards



Hi all,

I have problem with adding new (created) entity that has reference(s) on another entity. I use ObjectContext.AddObject method.

For example I have Employee entity with following properties:


EmployeeOfficeId (reference to Office entity)






EmployeeOfficeId is foreign key to OfficeId field of Office table in database.

Client is WinForm application and contain following code:

Code Snippet

privateLunchContractClient proxy = newLunchContractClient();

Employee emp = newEmployee();

Office office = proxy.GetOffices().Find(x => x.OfficeId == 1);

emp.EmployeeUserName = "User";

emp.EmployeeFullName = "FullName";

emp.EmployeeCreatedDateTime = DateTime.Now;

emp.EmployeeIsBlocked = false;

emp.EmployeeIsDeleted = false;

emp.Office = office;

proxy.AddUser(emp); // Call proxy method for add new user

Server is WCF-service application and contain following code in service contract implementation:

Code Snippet

publicvoid AddUser(Employee employee)





In fact EmployeeRepository derived from base Repository class that actually some wrapper for working with Entity Framework. Therefore actually calling base repository method Add:

Code Snippet

publicvoid Add(T entity)


   if (entity == null)

       thrownewNullReferenceException("Entity can't be a null object");

   _objectContext.AddObject(_entitySetBase.First().Name, entity); // I have exception when this line of code executes


When _objectContext.AddObject executed the following exception occurs:

Code Snippet

The object cannot be added to the ObjectStateManager because it already has an EntityKey.
Use ObjectContext.Attach to attach an object that has an existing key.

So Employee.EntityKey is null when i created it on client, but Employee.Office.EntityKey is NOT null, because I get it from model. As i understand correctly, Entity Framework goes through all object graph and if it find at least one EntityObject with filled EntityKey it fails.

I also try to Attach Employee.Office on object context before I call _objectContext.AddObject(), but in this case I get following error:

Code Snippet

An object with the same key already exists in the ObjectStateManager.
The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager
again if it is in the added state.

The question is how i can add new object with filed references in Entity Framework?


I keep getting the following InvalidOperationException:

The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.

when trying to do the following code:

newCorr.ReqCode = (from req in context.ReqCodeSet
          where req.Code.Equals(requirement.Code)
          select req).FirstOrDefault();

Just before this line, I am doing the following:

foreach (Requirement requirement in myInformation.Reqs)
   MyHwReqCorr newCorr = new MyHwReqCorr();

   newCorr.HwItem = Dictionaries.Instance.HwIdHwRecordDictionary[requirement.Id];

So what I'm doing is parsing through the my Information.Reqs list, creating a new instance of MyHwReqCorr, setting the HwItem to an item that was stored in a dictionary earlier on, and then setting the ReqCode by using a LINQ to SQL command which to look in a table for a req code that matches the one I'm passing in. Any help would be greatly appreciated. Any info you need, I'd be happy to provide.

EDIT: Right before I call this foreach, I can call this (as testing to verify that I can access the db):

List<ReqCode> reqCodeList = (from req in context.ReqCodeSet select req).ToList();

And I never get any errors with that. But when I try to set an item in that list (using the where extension method like:

newCorr.ReqCode = reqCodeList.Where(t=>t.Code == requirement.Code).FirstOrDefault();

) or using a dictionary as done similar to the newCorr.HwItem, I get the main error.



I am working on Entity Framework V.0 i am using  public void AddObject(string entitySetName, object entity) method, it works fine at runtime without exception but do not insert any row in my table.


 public void Add(T entity)
           this.ObjectContext.AddObject(GetEntitySet<T>(this.ObjectContext).Name.ToString(), entity);

        public EntitySetBase GetEntitySet<TEntity>(ObjectContext context)
            EntityContainer container = context.MetadataWorkspace.GetEntityContainer(context.DefaultContainerName, DataSpace.CSpace);

            EntitySetBase entitySet = container.BaseEntitySets.Where(item => item.ElementType.Name.Equals(typeof(TEntity).Name))

            return entitySet;






I'm trying to determine the best (or possibly only) way to design a WF w/ EF. Is it possible to pass an EF ObjectContext into a WF, have the WF use the object context for the lifetime of the WF and then have the ability for the host to do some more work against the ObjectContext? Is there a way that if on the root activity, I declare a variable w/ a default of say New ObjectContext() that I can have the WF call dispose on the context when the WF completes/terminates? Thanks!


I write ObjectContext class using singleton model .

public class ContextFactory
        private static TestEntities te = null;
        public static TestEntities Entities
                if (te == null)
                    te = new TestEntities();
                    if(te.Connection.State == ConnectionState.Closed)
                return te;

and a get method to get a depart object from db.

public Department get(int id)
            TestEntities te = ContexFactory.Entities;
                Department d= te.Department.FirstOrDefault<Department>(it => it.DepartmentID == id);
                return d;

I debug the get function, it works well the first time, but the second time(The vs2010 is not restarted), an error is opened.


the ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

It seems that the te object is still in the memory,  but te.Connection has been disposed. As the te.Connection property is readonly, I can not start a new Connection in current context. So how can i make a sigleton object of ObjectContext?

  Thanks in advance

When I attempt to construct an ObjectContext, the debugger hangs on the first line (the declaration) of the constructor:
var  objectContext = new  ProductCatalogEntities ();
Hangs here:
public  ProductCatalogEntities() : base ("name=ProductCatalogEntities""ProductCatalogEntities" )

Hitting the Break All button brings up the disassembly window at the following line:

00000013  mov         esi,eax

at this address


I'm not sure what's going on here.  Any ideas?  Thanks!

P.S. I'm trying to extend the PivotJitServer example (http://www.getpivot.com/developer-info/jit-tools.aspx) by wiring it up to some DZIs persisted in a SS DB.



Hi , 

Can anyone tell me how to use the following ObjectContext constructor : 


 public ReportingEntities(string connectionString) : base(connectionString, "ReportingEntities")


            this.ContextOptions.LazyLoadingEnabled = true;



I am trying to pass the connection string in following way so that I can point the model to any DB at run time. 

ReportingEntities reporting = new ReportingEntities(String.Format("metadata=res://*/ReportingEDM.csdl|res://*/ReportingEDM.ssdl|res://*/ReportingEDM.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=<<DBServerName>>;Initial Catalog=<<DBName>>;User ID=<<username>>;Password=<<password>>!;MultipleActiveResultSets=True&quot; providerName=\"System.Data.EntityClient\""));


But this gives me errors saying 'Undefined Keyword 'Data Source''. I have tried multiple combinations of connection strings but still same error. 



Is there any specific way to pass the connection string that I am not aware of? 


Please reply.




Performance tester


I have two entities in my DomainService: Entity A associates with Entity B (one A value has many B values). I have a getB() method to return a set of data. I found that: this.ObjectContext.A and this.ObjectContext.B are not null but this.ObjectContext.B.A is null. How could i use this.ObjectContext.B.A?

Please help,



I need to have in my EF model (default model using ObjectContext) some entities persisted on Sql server but I need some entities that work only in memory these temporary entities are filled with data at application start and are frequently updated, but have not to be persisted with savechanges. I need this in-memory entities in the same context with others because of some associations with persited entities. I do not found a way to do this. I do not find any info on how to make it possible. May be one entity option already available or to be implemented on future releases?

Help required thanks.


Hi. I have a page like Order - Order lines. Order represents by some textboxes and ddls, Order lines represents by GridView.

I want to let users add order lines without save changes to database. For example: he adds 4 order lines, fill order info and then hit Save button. Only an that moment all information should be saved to DB.

When I use code like

using (Entities ctx = new Entities())
 //create new OrderLine
 OrderLine ol = OrderLine.CreateOrderLine(1, 1, "", 1);
 //add OrderLine to OrderLines collection

newly created OrderLine does not appears in my object context, so I can't access it and bind GridView to new OrderList collection.

How can I use this scenario?



Hi ,

I created a model and generated the Database using this model.

and i added a list to the database using my UI (AddMovielist()--> method in Moviesclass)

MY UI have Moviename text box where the user can add this field to the database

The fields in the MOVIE database are MOvie ID(GUID)  and MovieName

and i created a dll  using the above application...


NOW i  created an other application and added the above application dll as reference

Now i had 3 fields in the UI  ( 1.Director name 2.release date 3.Moviename )

When i update my movieName

The movie name should be saved in my movie database and Director name ,release date should be saved in an other database which should be dynamically generated with refrence to the MOvie ID(GUID) .

Can any one suggest me how to solve this ..

Thanks in Advance



I have created an entity model off a database with an 'Item' table and a 'Request' table (FK between them on the ItemID column). In my entity model I have removed the association between Item and Request, deleted the 'ItemID' column from the Request entity and set the base type of my 'Request' entity to 'Item'. I have set the mapping for the ItemID Value/Property of my Request entity to ItemID from the drop down list and have built the solution.

When I add a domain context to the project, the Item entity is selectable from the Entities check box list, but the Request entity is visible, but greyed out and un-selectable.

I have not set my Item entity as abstract as I want to be able to query this entity seperately so don't know if this is the reason that I can't select it in the list?

I want to be able to select the Request entity in this list. Does anybody have any suggestions as to what I have done wrong, or not done???

Thanks in advance,


Hi All,

When I add new entity on CRM 3, there is some errors occur : "An Error has occurred. For your information, contact your system administrator.", it also appears when i add/edit/remove attribute from some custom entity (not all entity, for some others, it just work well).

Does anybody face this problem before?

how can i solve it?

fyi, i'm googling before about this situation, and found this link

"http://support.microsoft.com/kb/934690" i followed the solution, but it just not worked.

thx before for your helps.




Hello friends,

I've got a really big problem. I'm currently working at a company and finalising my a-level-exam-project.

In recent tests I realised that on some PC's the application is extremely slow (takes 5 minutes to start and is slow after this too.)

With the help of the debugger I found out that it takes a really long time to execute the following query:




<Menu> menuEntries = kitchenManagerEntities.Menu.Include("Users").Include("Categories").Include("Helptasks").Where(m => m.Date > elemsFrom && m.Date < elemsTo);

This should retrieve about 700 Menu elements including about 200 users, a few categories and up to 500 helptasks. Which should not be much for the database server of the company (SQL Server 2008). The database is really tiny, it only has 7 tables.

But now the strange things:

If I wait for the application until it starts or Windows thinks it has died and I close it, I only have to restart it and it works.

I also tested a local SQL-Database (SQL Server Express) on the problematic computers but it also results in the same problem. I updated the network driver because I thought it might be a possible solution to the problem because of the network infastructure (which is a bit complicate here, because they use Novell Zenworks) .But after the next reboot I have to repeat the same procedure if I want to use a fast application.

Some details about my application:

Desktop Application with .Net Framework 3.5 SP1, WPF, MEF, WPF Application Framework and of course the Entity Framework

I also ported the application to .Net 4.0, but I got another failure too and the old one still exists so I decided to use the feature "Undo Pending Changes" :-)

thanks for your help

if you need any further details, please let me know!

nice regards



We have a pretty simply SQL CE Database that is accessed using the ADO .NET Entity Framework. The Database is part of a Desktop Application, so startup time is crucial. On 4 out of the 5 computers we have run the code on, the load time and initial query is fast ( < 1s). These 5 computers have been a mix of development environments and test environments. On one particular computer (which happens to be my development machine!) the first query takes about 4 seconds. On my computer I created a brand new project, and a brand new Database. The Database only has one table with 3 columns, (a bigint, a varchar and a Date). The table only has two rows of a data in it. Even with this very minimal configuration it still takes roughly 4 seconds to simply get the count on the table.

As a separate test I also tried accessing the Database using the SqlCeConnection and SqlCeDataReader, and it is practially instantanious to connect and run a query, so it really seems like the problem is with the Entity Framework and not the SQL CE Database.

Finally, I tried pre-generating the views, this made it slightly faster, maybe 3 seconds instead of 4, but still much slower than the other 4 computers.

I spent hours scouring the net and could not find reference to the Entity Framework being slow on a particular computer but not on others. Has anyone heard of a problem like this before?





I have already asked this same question at stackoverflow but it doesn't look like anyone has an answer so i was hoping that i might get one here instead.

As the title suggest i'm having a problem with the first query against a MS SQL database using the Entity Framework. I have tried looking for an answer on different sites but no one seems to actually have a solution to this.

I'm loading quite a lot of rows from the database including two 0-many relationships. The tests was done in Visual Studio 2010 using the Entity Framework 4.0 Model and the POCO generator (there isn't much difference in timings between normal entities and POCO objects). I also used the T4 Views Template to pre-compile the views. The database was on a MS SQL Server 2008.

What i would really like to know is why the first query is soo much slower than any secondary queries. I also wanna know if something can be done to increase the speed of the first query to a point where it is within acceptable limits. This is a big query and we may get other queries that are even bigger and it is understandable that they may be a bit slow but 30 seconds is way too slow for user to wait for especially when datasets can get the same data a lot faster.

I have done some timing tests to try and find out where the problem lies and i was a bit surprised to see that it looks like it is the SQL server that is slow on the first query. Timings was as follows:

.NET testing application.
- First Query: 29,6 seconds
- Second Query: 3,2 seconds

SQL Profiler
- First Query: 27 seconds
- Second Query: 3,2 seconds

SQL Server Query Window
- First Query: 8 seconds
- Second Query: 4 seconds

Timings in the application was measured with the Stopwatch. Only the query was measured and .ToList() was used to execute the query.

Timings in the SQL Profiler is for the same queries that was executed in the application which shows that the application only use about 2,6 seconds to fill data into the objects. The last 27 seconds is used for executing the query on the SQL server.

Looking at the secondary query the timings are the same for both application and SQL server but executing the query is much faster this time. I can understand why the application doesn't use any time because there is no new rows that need to be converted to objects but why is the query so much faster, i would have expected a few seconds because of execution plans but not 24 seconds.

Just for testing purpose i copied the SQL that the Entity Framework generates and opened a new query window with a separate connection and executed the query in it. As you can see it takes 8 seconds for the first query and 4 seconds for the second.

I hope someone have some suggestions.
ps. I apologize for the wall of text :)


Its ugly browser.. the tabs to side the adress bar?

And in de classic mode it likes ie8.

The options is the same.


One tip for Microsoft make it FASTER, BETTER SMOOTHER!


I'm trying to delete an object graph using Entity Framework, but Entity framework is issuing some erroneous SELECT statements causing massive slowdown.    

Here is the code that is causing me problems:  

    Dim existingQuery = SomeContext.Queries.FirstOrDefault(Function(q) q.QueryId = 123)
    query.QueryGroupId = existingQuery.QueryGroupId
    Dim detailsToDelete = New List(Of QueryDetail)
    ForEach queryDetail As QueryDetail In existingquery.querydetails
    ForEach queryDetail As QueryDetail In detailsToDelete
        //This is loading 25,000 CriteriaColumnType entities...why?

My object graph looks something like this (simplified)

    int QueryId  
    string QueryName  
    List(Of QueryDetail) QueryDetails  
    int QueryDetailId  
    Query Query  
    int QueryId  
    CriteriaColumnType CriteriaColumnType  
    int CriteriaColumnTypeId  

The DeleteObject(entity) call is running a query something like this:  
FROM QueryDetail
WHERE CriteriaColumnTypeId = (CriteriaColumnTypeId from the QueryDetail record being deleted)

In this case this select criteria brings back around 25,000 rows...which obviously drags down my performance.  

How do I stop these selects from occuring?

**Interesting note:  
If I put a `SomeContext.ContextOptions.LazyLoadingEnabled = False` directly before "`DeleteObject`" then the selects don't happen.

If it matters, I am using the POCO templates for my entities.


Hi guys,


just a quick poco question, setup is EF4, POCO objects, ProxyCreationEnabled turned on.

After calling CreateObject<T>() is the newly created poco proxy added automatically to the ObjectContext or one must explicitly add it via AddObject(). Or is it more performant to first manually instantiate the poco, init it with what is needed, and then add it via AddObject() ?

I have this code that is blowing up during the SaveChanges.

The entities are :

TJUsers 1---* Clips 1----* SubClips

I have already added an user, but now I am trying to add a clip and I get
the expection:

{"Cannot insert the value NULL into column 'Hash', table 'atalkjunkydb.talkjunky.Clips'; column does not allow nulls. INSERT fails.\r\nThe statement has been terminated."}

I have confirmed that newClip.Hash and clip.Hash are both value and non-null.  

Suggestions on how to debug this?


 public void SaveClips(ClipSync[] clips)

            TalkJunkyEnititesContainer tjdb = new TalkJunkyEnititesContainer(connStr);
            foreach (var clip in clips)
                var rcClip = (from c in tjdb.Clips
                              where c.Hash == clip.Hash && c.TJUserId == tjuser.Id
                              select c).SingleOrDefault();
                if (rcClip == null)  //new clip

                    Clip newClip = new Clip();
                    newClip.Hash = clip.Hash;
                    newClip.TJUserId = tjuser.Id;
                    newClip.AddedDate = DateTime.Now;
                    newClip.Comments = clip.Comments;
                    newClip.FileName = clip.Filename;
                    newClip.LastListenDate = clip.LastListen;
                    newClip.LastLocation = clip.LastLocation;
                    newClip.Length = clip.Length;
                    newClip.PlayCount = clip.PlayCount;
                    newClip.Played = clip.Played;
                    newClip.Priority = clip.Priority;
                    newClip.Rating = clip.Rating;
                    newClip.RecUpdate = clip.RecUpdate;
                    newClip.Track = clip.Track;
                    newClip.TitleDate = clip.TitleDate;
                else //update



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure