Entity Framework Core DbContext Updated

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" };
context.Add(author);
context.SaveChanges();

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" }
    }
};
context.Add(author);
context.SaveChanges();

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" }
};
context.AddRange(books);
context.SaveChanges();

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);
context.SaveChanges();

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 };
context.Remove(author);
context.SaveChanges();

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)
{
    context.Update(author);
    context.SaveChanges();
}

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.

Summary

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.