Jupaol
Jupaol

Reputation: 21365

EntityFramework adding new object to a collection

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???

Upvotes: 2

Views: 5729

Answers (1)

Yusubov
Yusubov

Reputation: 5843

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.

Upvotes: 5

Related Questions