2

Probably this question has been answered before, if that's the case I would appreciate if you guys point me in the right direction.

I would like to know what happens when a new object is added to an EntityFramework collection.

More precisely, I'd like to know if in order to add the new object the whole collection is loaded into memory

For example:

public class MyContext : DbContext
{
    public DbSet<Assignment> Assignments { get; set; }
}

public class SomeClass
{
    public void AddAssignment(Assignment assignment)
    {
        var ctx = new MyContext();

        ctx.Assignments.Add(assignment);

        ctx.SaveChanges();
    }
}

Do all the assignment records have to be loaded into memory just to perform a simple insert???

1 Answer 1

5

In short: no load process of entire entity collection.

The AddObject() method is used for adding newly created objects that do not exist in the database. When AddObject() is called, a temporary EntityKey is generated and the EntityState is set to 'Added', as shown below:

enter image description here

When context.SaveChanges() is called, EF 4.0 goes ahead and inserts the record into the database. Note that Entity Framework converts the code into queries that the database understand and handles all data interaction and low-level details. Also notice in the code above, that we are accessing data as objects and properties.

After you have executed the code, you can go ahead and physically verify the record in the database.

Sign up to request clarification or add additional context in comments.

3 Comments

I just added a new question, could you please share your knowledge with me again =)? stackoverflow.com/q/13868030/1268570
Sure, no problem, i will look at that shortly.
Funny, i'm actually looking at profiler right now and experiencing the complete opposite of what you just said. The entire collection is fetched before the new item is added.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.