Entity Framework Core DbContext Updated

4.5 (6 votes)

Redesigning a framework from the ground up provides an opportunity to implement an improved API. The team working on Entity Framework Core have certainly grabbed that opportunity in respect of the DbContext class, which sees a bunch of new data manipulation methods not available in Entity Framework 6 or earlier.

In previous versions of Entity Framework that include the DbContext (EF 4.1.1 onwards), data manipulation (create, update and delete) operations are performed against the relevant entity's DbSet property. In Entity Framework Core, these operations can now also be performed directly against the DbContext.

Adding Data

The DbContext provides a couple of methods for adding data: Add and AddRange. There are two versions of the Add method which is designed for adding a single instance of an entity to the database - a generic one and one that takes an object as a parameter. You are most likely to use the generic version:

var author = new Author { FirstName = "William", LastName = "Shakespeare" };

The Add method results in the entity being tracked in the Added state. When the SaveChanges method is called, Entity Framework Core resolves the type passed in to the Add method and generates the appropriate SQL to ensure that the entity is added to the correct table in the database. If you pass in an object graph, any entities that aren't already being tracked will be tracked in the Added state. In the next example, INSERT statements will be generated for the author and all of the books:

var author = new Author
    FirstName = "William",
    LastName = "Shakespeare",
    Books = new List<Book>
        new Book { Title = "Hamlet"},
        new Book { Title = "Othello" },
        new Book { Title = "MacBeth" }

All of the entities are added in the previous example by virtue of the relationship between them. If you want to add multiple unrelated objects, you can use one of two version of the new AddRange methods. One takes a collection of the same type of object:

var books = new List<Book> {
    new Book { Title = "It" },
    new Book { Title = "Carrie" },
    new Book { Title = "Misery" }

The other takes a params array of objects:

var book = new Book { Title = "It" };
var product = new Product { ProductName = "Sugar" };
var comment = new Comment { Content = "Hello World" };
context.AddRange(book, product, comment);

Entity Framework Core is able to resolve the different types passed in to this method and generate the appropriate SQL for each one.

Removing Data

The Remove method is provided for deleting data. Here's an example that uses a stub to represent the entity to be deleted:

var author = new Author { AuthorId = 1 };

Updating Data

As with previous versions of Entity Framework, if you modify any of the properties of an entity that is being tracked, its state will be set to Modified and an UPDATE statement will be generated when SaveChanges is called. In disconnected scenarios, you had to use the Attach method to get the context to start tracking an entity and then explicitly set its state to Modified to ensure that the UPDATE statement is generated when working with earlier versions of Entity Framework. A new method: Update has been introduced in Entity Framework Core to cater for disconnected scenarios. The next example illustrates a simple service method that receives an entity from somewhere else - serialized from JSON in a Web API end point, perhaps. It is assumed to have been modified in some way:

public void Save(Author author)

The Update method ensures that the entity's state is set to Modified, and SQL will be generated to update all of the entity's properties to the current values. It is a shortcut to using Attach and setting state explicitly. The Update method is also available on the DbSet property.


This article illustrates the new CUD methods that have been added to the DbContext class in Entity Framework Core. As well as making a nicer API, these methods aid cleaner reusable code creation, since you no longer have to involve the DbSet type when performing CUD operations.

See more about Entity Framework Core at Learn Entity Framework Core.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 3962

1 Comment

- Manoj Kulkarni

Great post.

Recent Comments

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...