Entity Framework Core – Difference between Add, Entry and Attach methods

Let’s see the difference between the Add, Entry and Attach methods of Entity Framework Core.

Add is to indicate to the Entity Framework that we are going to want to insert a new record in the database.

In contrast, Entry and Attach are used in scenarios where the record already exists in the database, and we simply want to make some kind of modification on it.

In the case of Attach, the object is analyzed recursively and all the related entities are taken into account. In the case of Entry, only the object you pass to the Entry method is taken into account, and not its related entities. For example: Suppose we have the Student and Contact entities. Where each Student has a corresponding list of Contacts (one to many relationship). Let’s see an example of Entry:


Student student1;
using (var context = new ApplicationDbContext())
{
   student1 = context.Students.First();
}

student1.Contacts = new List<Contact>();
student1.Contacts.Add(new Contact() { Name= "Contact 1" });

using (var context = new ApplicationDbContext())
{
   var entry = context.Entry(student1);
   // Only the student entity will be updated, ignoring the contact 
   entry.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
   context.SaveChanges();
}

Only the Student is updated. However, if we use Attach:


Student student1;
using (var context = new ApplicationDbContext())
{
student1 = context.Students.First();
}

student1.Contacts = new List<Contact>();
student1.Contacts.Add(new Contact() { Name = "Contact 1" });

using (var context = new ApplicationDbContext())
{
   var attach = context.Attach(student1);
   // The student will be updated and a contact is going to be created.
   attach.State = Microsoft.EntityFrameworkCore.EntityState.Modified;
   context.SaveChanges();
}

Then the student is updated and a contact is created. It is important to note that if the contact has its primary key set, then by default Entity Framework Core will not do anything with the contact.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s